2014-11-05 105 views
1

我有一個窗體,裏面有幾個文本框和幾個按鈕。我有幾個自定義表單元素,我正在處理。其中一個特別是一個文本框,它將搜索一個數據庫onEnterClicked。這工作得很好,但我也有一個按鈕,將運行代碼onClick。這兩個似乎都與提交表單有關。防止表單從觸發按鈕提交

<form onsubmit="return false;"> 
    <input type="text" id="autofill"> 
    ... 
    <button id="upload"> 

當我運行此jQuery代碼:

$("input#autofill").keyUp(function(e){ 
    //Do stuff 
}); 

$("button#upload").click(function(){ 
    alert("test"); 
}); 

按下自動填充文本框中輸入將顯示測試警報,但不會做任何//do stuff代碼。

我怎樣才能防止這種情況發生?

$(function(){ 
 
    
 
    $("#autofill").keyup(function(e){ 
 
    
 
    if(e.keyCode == 13) 
 
    alert("Enter pressed"); 
 
    
 
    }); 
 
    
 
    $("#upload").click(function(){ 
 
    
 
    alert("Button clicked"); 
 
    
 
    }); 
 
    
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<form onsubmit="return false;"> 
 
    <input type="text" id="autofill"/> 
 
    <button id="upload">Click me to show an alert</button> 
 
</form>

+0

這是很難理解你正在試圖完成的任務。 – EternalHour 2014-11-05 04:04:13

+0

@EternalHour當我按下文本框中的回車鍵時,我希望'//做些東西'運行;現在它顯示'alert(「test」)',當它不應該時,就像我在代碼片段中顯示的那樣。嘗試按下輸入文本框中。它會顯示「Button Clicked」而不是「Enter pressed」 – David 2014-11-05 04:05:30

回答

5

爲了防止形式與<button>提交,你需要指定type="button"

<button id="upload" type="button">Click me to show an alert</button> 

如果不指定type,默認是type="submit",當你按ENTER鍵將提交表單。

+0

謝謝布魯!有用 :) – David 2014-11-05 04:34:10

1

如果您有很強的使用按鈕類型'submit'的理由,那麼試試這個解決方案。捕捉文本框的「按鍵」事件,並抑制其

$(function() { 
 

 
    // handle the 'keypress' event to prevent the form submission 
 
    $('#autofill').keypress(function(e) { 
 

 
    if (e.keyCode == 13) { 
 
     e.preventDefault(); 
 
     e.stopPropagation(); 
 
    } 
 

 
    }); 
 

 
    $("#autofill").keyup(function(e) { 
 

 
    if (e.keyCode == 13) 
 
     alert("Enter pressed"); 
 

 
    }); 
 

 
    $("#upload").click(function() { 
 

 
    alert("Button clicked"); 
 

 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<form id="f"> 
 
    <input type="text" id="autofill" /> 
 
    <button id="upload">Click me to show an alert</button> 
 
</form>