我有一个带有两个文本框的表单,一个选择下拉框和一个单选按钮。当按下enter键时,我想调用JavaScript函数,但当我按下它时,表单就提交了。
当按下回车键时,如何防止表单被提交?
我有一个带有两个文本框的表单,一个选择下拉框和一个单选按钮。当按下enter键时,我想调用JavaScript函数,但当我按下它时,表单就提交了。
当按下回车键时,如何防止表单被提交?
当前回答
下面是如何使用JavaScript来完成它:
//in your **popup.js** file just use this function var input = document.getElementById("textSearch"); input.addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { alert("yes it works,I'm happy "); } }); <!--Let's say this is your html file--> <!DOCTYPE html> <html> <body style="width: 500px"> <input placeholder="Enter the text and press enter" type="text" id="textSearch"/> <script type="text/javascript" src="public/js/popup.js"></script> </body> </html>
其他回答
有点简单
不要按“Enter”键发送表单:
<form id="form_cdb" onsubmit="return false">
按“Enter”键执行功能:
<input type="text" autocomplete="off" onkeypress="if(event.key === 'Enter') my_event()">
使用两个事件。which和event.keyCode:
function (event) {
if (event.which == 13 || event.keyCode == 13) {
//code to execute here
return false;
}
return true;
};
如果你正在使用jQuery:
$('input[type=text]').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
<div class="nav-search" id="nav-search">
<form class="form-search">
<span class="input-icon">
<input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
<i class="ace-icon fa fa-search nav-search-icon"></i>
</span>
<input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
</form>
</div>
<script type="text/javascript">
$("#search_value").on('keydown', function(e) {
if (e.which == 13) {
$("#search").trigger('click');
return false;
}
});
$("#search").on('click',function(){
alert('You press enter');
});
</script>
jQuery解决方案。
我来这里寻找一种方法来延迟表单提交,直到文本输入上的模糊事件被触发。
$(selector).keyup(function(e){
/*
* Delay the enter key form submit till after the hidden
* input is updated.
*/
// No need to do anything if it's not the enter key
// Also only e.which is needed as this is the jQuery event object.
if (e.which !== 13) {
return;
}
// Prevent form submit
e.preventDefault();
// Trigger the blur event.
this.blur();
// Submit the form.
$(e.target).closest('form').submit();
});
最好能有一个更通用的版本,可以触发所有延迟事件,而不仅仅是表单提交。