2014-01-24 278 views
0

我有一個表單,在輸入文本框中我輸入一個數字,然後按ENTER鍵,我用jQuery將值附加到textarea。這一切工作正常。jQuery,防止表單提交輸入,但允許表單提交按鈕點擊

我遇到的問題是,如果我添加一個提交按鈕來提交表單,只要我按下ENTER鍵,它就會提交表單。

我想要它做的不是按下輸入提交表單,而是在提交按鈕被單擊時提交表單。

我試過使用preventDefault()並返回false,這將停止按ENTER鍵提交的表單,但如果我在提交按鈕上添加一個單擊事件來提交表單,它什麼都不做。我把警報在點擊功能之前提交和火災,但形式不提交

<form id="toteform" method="post" action="blah.php"> 
    <input type="text" name="bin" id="bin" maxlength="4" autocomplete="off" /> 

    <input type="text" name="totes" id="tote" maxlength="4" autocomplete="off" /> 

    <input type="button" name="submit" class="submit" id="submit" value="Submit" /> 
</form> 

jQuery的

$("#submit").click(function() { 
    $('#toteform').submit(); 
}); 

$('#bin').focus(); 

$('#bin').keypress(function(e) { 
    if(e.which == 13) { 
     $('#tote').focus(); 
    } 
}); 

$('#tote').keypress(function(e) { 
    if(e.which == 13) { 

    // more code here to do other things 

回答

0

我找到了解決辦法

$("#toteform").submit(function(e) { 
    if (e.originalEvent.explicitOriginalTarget.id == "submit") { 
     // let the form submit 
     return true; 
    } 
    else { 
     //Prevent the submit event and remain on the screen 
     e.preventDefault(); 
     return false; 
    } 
}); 
1

您可以防止表單提交

$("#toteform").on('submit',function(e) { 
    e.preventDefault(); 
}); 

和點擊提交按鈕,您可以手動提交表單。

$("#submit").click(function() { 
    $('#toteform').submit(); 
}); 
+0

感謝您的回覆,我改變了按鈕的輸入類型提交和兩種輸入類型,他們仍然不提交表單。我在#submit click事件中添加了一個警報,只要輸入一個值並按下ENTER,警報就會打開,不需要點擊按鈕。 – AdRock

6

小心與e.originalEvent.explicitOriginalTarget.id方法。 它只適用於Gecko based browsers

相關answer

會使用一個評論,但我沒有足夠的聲譽:(

+0

有另外10個代表可以讓您的評論技巧提升。 – MrMarlow