2016-08-12 82 views
0

我有一個JavaScript函數,它可以處理按鈕單擊事件。只有當總體表單驗證返回true時,我才需要該函數才能工作。我正在使用jquery驗證插件來驗證表單。驗證工作正常,但是當我單擊按鈕時,即使驗證存在,仍會進入函數內部。即使驗證成功,按鈕點擊事件仍在運行

我打電話的功能是這樣的:

document.getElementById('btnNext').addEventListener('click', handleFileSelect, false); 

function handleFileSelect(evt) { 
//My Code goes here 
} 

//This is my form.. 

<form id="someID"> 
<button id ="next" type="submit"> 
</form> 

//And my validation will be as follows: 

$("#posterForm").validate({ 
    rules: { 
     //Here all the validation rules 
    }, 
    messages: { 
     //Here all the error messages 
    } 

}); 

回答

1

你混合DOM和jQuery事件偵聽器。行document.getElementById('btnNext').addEventListener('click', handleFileSelect, false);正在監聽dom事件。你可以做

$('#btnNext').on('click', function(evt){ 
    //Validate the fields 
    var valid; 
    //set the valid field to true if the fields are true else set to false 
    if (!valid) 
    evt.preventDefault(); 
}); 

preventDefault doc詳細介紹了這個功能。