2011-05-06 190 views
4

我試圖阻止提交使用提交eventlistener的表單。我的匿名函數運行,但表單仍然提交,即使函數結束時返回false。沒有JS錯誤被拋出。用提交eventlistener停止表單提交

我在犯些愚蠢的錯誤嗎?

<form id="highlight"> 
    Row: <input type="text" name="rows" value="1" id="rows"> 
    Column: <input type="text" name="cells" value="1" id="cells"> 
    <input type="submit" name="Submit" value="Highlight" id="Submit"> 
</form> 

<script> 
var highlight_form = document.getElementById('highlight'); 
highlight_form.addEventListener('submit', function() { 
     alert('hi'); 
    return false; 
}, false); 
</script> 
+0

[addEventListener提交表單返回false仍然可以提交表單?](http://stackoverflow.com/questions/4924036/return-false-on-addeventlistener-submit-still-submits-the-form) – unor 2013-09-16 11:38:18

回答

9

我一直呼籲,我想取消該事件的事件偵聽器event.preventDefault(),以及回報false。這總是適合我。

<script> 
var highlight_form = document.getElementById('highlight'); 

highlight_form.addEventListener('submit', function(event) 
{ 
    event.preventDefault(); 
    alert('hi'); 
    return false; 

}, false); 
</script> 
+0

當我更改返回false返回true(或返回)時,不適用於我。 – zeuf 2014-06-13 13:34:17

+0

@zeuf並仍然使用'event.preventDefault()'或否? – 2014-06-13 17:10:06

1

爲了防止表單提交,我一直使用的「點擊」事件來調用JavaScript方法,將做一些事情,然後從那裏提交。您還可以設置如下形式:

function validateForm() 
{ 
var x=document.forms["myForm"]["fname"].value 
if (x==null || x=="") 
    { 
    alert("First name must be filled out"); 
    return false; 
    } 
} 
0

嗯,這是我會做的方式:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post"> 
First name: <input type="text" name="fname"> 
<input type="submit" value="Submit"> 
</form> 

提交後,validateForm()方法可以在必要時阻止提交

function validate (form) 
{ 
    // return false if some fields are not right 
} 

function setup_form_validation (form) 
{ 
    form.addEventListener (
     'submit', 
     function (f) { // closure to pass the form to event handler 
      return function (evt) { 
       if (!validate (f)) evt.preventDefault(); 
       // Return status doesn't work consistently across browsers, 
       // and since the default submit event will not be called in case 
       // of validation failure, what we return does not matter anyway. 
       // Better return true or nothing in case you want to chain other 
       // handlers to the submit event (why you would want do that is 
       // another question) 
      }; 
     } (form), 
    false); 
} 

雖然我寧願有一個布爾值來保存表單驗證狀態。每次字段更改時更好地更新狀態,而不是僅在用戶嘗試提交整個表單時進行檢查。

當然這會在IE8和其他舊瀏覽器中失敗。您需要另一個血腥事件抽象層才能使其在任何地方都能正常工作。