2013-02-22 50 views
8

提交按鈕,我想阻止提交與onclick事件提交按鈕:防止onclick事件從提交

$j('form#userForm .button').click(function(e) { 
    if ($j("#zip_field").val() > 1000){ 
     $j('form#userForm .button').attr('onclick','').unbind('click'); 
     alert('Sorry we leveren alleen inomstreken hijen!'); 
     e.preventDefault(); 
     return false; 
    } 
}); 

這是提交按鈕:

<button class="button vm-button-correct" type="submit" 
onclick="javascript:return myValidator(userForm, 'savecartuser');">Opslaan</button> 

它會顯示「警報「功能,並且還會刪除onclick事件,但表單無論如何都會被提交。在提交之前手動刪除onclick事件將解決問題。然而,這是核心功能,我不想刪除它。

編輯:

這肯定通過的onclick選擇造成的。我怎麼能強迫我的jQuery腳本立即重新加載onclick事件?加入jQuery代碼之前:$j('form#userForm .button').attr('onclick','');會解決問題。但是我的驗證將無法正常工作的了...

+0

你應該真正做到這一點的形式提交處理..如果你按下回車鍵當表單有焦點..它會觸發提交處理程序,而不是你的點擊,因此你的驗證將被繞過 – 2013-02-22 15:44:15

回答

18

你需要將事件添加作爲參數:

$j('form#userForm .button').click(function(event) { // <- goes here ! 
    if (parseInt($j("#zip_field").val(), 10) > 1000){ 
     event.preventDefault(); 
     $j('form#userForm .button').attr('onclick','').unbind('click'); 
     alert('Sorry we leveren alleen inomstreken hijen!'); 
    } 
}); 

而且,val()總是返回一個字符串,所以一個好的做法是在將它與數字進行比較之前將其轉換爲數字,並且我不確定您是否真的在該函數內部針對#userForm內的所有.button元素,或者如果您應該使用而不是this

如果你使用jQuery 1.7+,你應該考慮使用on()off()

+0

thx,我編輯的代碼,但它不工作..我猜onclick事件打破prevent.default ...? – 2013-02-22 15:21:37

+0

內聯的onclick將始終首先執行,同時擁有這樣的內聯函數和事件處理程序並不是一個好習慣,您應該重新考慮這一點,並僅處理事件處理函數,然後調用'myvalidator ()'從外部事件處理程序。 – adeneo 2013-02-22 15:41:44

+1

很多thx!我現在發現了;)但是我不想打破virtmart的核心代碼。所以這就是爲什麼我試圖解決這個問題! – 2013-02-22 15:44:48

0

不要忘了,還有功能/事件參數,但必須指定的參數:

$("#thing").click(function(e) { 
    e.preventDefault(); 
}); 

通過這種方式,提交停止,所以你可以conditionalise它。

12

基本上,如果您將按鈕類型從type="submit"更改爲type="button",則此按鈕不會提交表單,也不需要解決方法。

希望這會有所幫助。

+0

很多thx ...但我很肯定onclick事件是責怪 – 2013-02-22 15:31:59

+0

這個答案解決了我的情況,對我來說這應該被標記爲正確的答案,因爲它更通用:)非常感謝! – 2014-07-03 13:47:56

+0

我正在使用JQuery驗證。我有一個'type =「button」'的按鈕,但仍然在驗證失敗時回傳表單! [Here](http://stackoverflow.com/questions/29890544/page-still-postbacks-after-jquery-validation-fail/29890940#29890940) 是我的問題。 – sohaiby 2015-04-27 08:58:37

0

最好的方法是在你的提交事件處理程序的表單中做所有事情。的onclick刪除內聯並運行它提交函數內部

$j('#userForm').submit(function(e) { 
    if (+$j("#zip_field").val() > 1000){ 
     alert('Sorry we leveren alleen inomstreken hijen!'); 
     return false; 
    } 
    return myValidator(userForm, 'savecartuser'); 
}); 
-2

我相信有一個簡單的方法:

$j('form#userForm .button').click(function(event) { // <- goes here ! 
    if (parseInt($j("#zip_field").val(), 10) > 1000){ 
     event.stopPropagation(); 
    } 
});