2011-10-18 24 views
0

我有一個完整的驗證碼綁定到$('#post-button').click。這個想法是,變量e_exit設置爲true,然後表單中的數據經過一系列檢查。如果它滿足任何if語句的條件,則會顯示一條消息,並將e_exit設置爲false。除了問題是,它沒有正確完成,因爲表單仍然提交(如顯示消息後的四分之一秒)。表單即使它被封裝在if語句中,但條件不符合?

我這裏處理布爾值,因此類型轉換肯定不可能是這個問題,我真不明白這是怎麼回事:

$('#post-button').click(function() { 
    var e_exit = true; 
    var notif_message = '<div class="notification red"><div class="cross"></div>'; 

    var name = $('input[name=name]').val(); 
    var url = $('input[name=url]').val(); 
    var urlrgx = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/i; 
    var urltst = urlrgx.test(url); 

    if(name == '' || name == 'Enter a name for this offer') { 
     $('#notification').html(notif_message + "You need to enter a name for this offer name. Try to pick something that you'll easily remember when seen again.</div>"); 
      e_exit = false; 
    } 

    if(!urltst) { 
     $('#notification').html(notif_message + "You need to enter a valid offer url prefixed with http:// for this offer.</div>"); 
      e_exit = false; 
    } 

    var rotation_select_val = parseInt($('select[name=r_id]').val()); 
    if(rotation_select_val != 0) { 
     var min_val = isNaN($('input[name=r_min]').val()); 
     var max_val = isNaN($('input[name=r_max]').val()); 

     if(min_val || max_val) { 
      $('#notification').html(notif_message + "You need to enter a numeric value for your rotation's min and max hits for this offer.</div>"); 
      e_exit = false; 
     } 
    } 

    var geo_select_val = $('select[name=g_country\\[1\\]]').val();   
    if(geo_select_val != 0) { 
     var geo_url_val = $('input[name=g_url\\[1\\]]').val(); 
     var geo_urltst = urlrgx.test(geo_url_val); 

     if(!geo_urltst) { 
      $('#notification').html(notif_message + "You need to enter a valid url prefixed with http:// for your geo-location targets.</div>"); 
      e_exit = false; 
     } 
    } 

    if(e_exit) { 
     $('form').submit(); 
    } 
}); 

任何答案,爲什麼這可能會發生,或編輯與解釋將是一個很大的幫助!

回答

0

如果#post-button是一個提交按鈕,則需要返回false來停止表單提交。

一個更好的解決辦法是綁定到窗體的submit事件:

$("#your-form").submit(function() { 
    // validate... 

    return e_exit; 
}); 

這將只允許表單提交,如果你從事件處理程序返回true

編輯:

也許AJAX插件還訂閱了click事件後按鈕?在這種情況下,我會返回false,並確保停止事件進一步傳播,像這樣:

$("#post-button").click(function(ev) { 
    // validation 
    ev.stopPropagation(); 
    return false; 
}); 
+0

這不是一個提交按鈕,問題是它已經綁定到一些給ajaxForm插件(我現在希望我沒有用過),我根本沒有時間重新整合所有的東西和ajaxForm插件,我寧願明白爲什麼'e_exit'設置爲false,它仍然會提交。 – Avicinnian

+0

看我的編輯,這可能會幫助你 –

+0

道具,你的編輯是在點:)。 – Avicinnian

相關問題