我有一个带有两个文本框的表单,一个选择下拉框和一个单选按钮。当按下enter键时,我想调用JavaScript函数,但当我按下它时,表单就提交了。
当按下回车键时,如何防止表单被提交?
我有一个带有两个文本框的表单,一个选择下拉框和一个单选按钮。当按下enter键时,我想调用JavaScript函数,但当我按下它时,表单就提交了。
当按下回车键时,如何防止表单被提交?
当前回答
在我看来,一个更简单有效的方法应该是:
function onPress_ENTER()
{
var keyPressed = event.keyCode || event.which;
//if ENTER is pressed
if(keyPressed==13)
{
alert('enter pressed');
keyPressed=null;
}
else
{
return false;
}
}
其他回答
原生js(获取api)
document.onload = (() => { alert('ok'); let keyListener = document.querySelector('#searchUser'); // keyListener.addEventListener('keypress', (e) => { if(e.keyCode === 13){ let username = e.target.value; console.log(`username = ${username}`); fetch(`https://api.github.com/users/${username}`,{ data: { client_id: 'xxx', client_secret: 'xxx' } }) .then((user)=>{ console.log(`user = ${user}`); }); fetch(`https://api.github.com/users/${username}/repos`,{ data: { client_id: 'xxx', client_secret: 'xxx' } }) .then((repos)=>{ console.log(`repos = ${repos}`); for (let i = 0; i < repos.length; i++) { console.log(`repos ${i} = ${repos[i]}`); } }); }else{ console.log(`e.keyCode = ${e.keyCode}`); } }); })(); <input _ngcontent-inf-0="" class="form-control" id="searchUser" placeholder="Github username..." type="text">
整个文档按下回车键:
$(document).keypress(function (e) {
if (e.which == 13) {
alert('enter key is pressed');
}
});
http://jsfiddle.net/umerqureshi/dcjsa08n/3/
<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>
事件。键=== "Enter"
使用event.key。不再有任意的数字代码!
注意:旧属性(。keyCode和.which)已弃用。
const node = document.getElementsByClassName("mySelect")[0];
node.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
// Do more work
}
});
现代风格,有lambda和解构
node.addEventListener("keydown", ({key}) => {
if (key === "Enter") // Handle press
})
Mozilla文档
支持的浏览器
我使用了document on,它涵盖了页面加载后动态添加的html:
$(document).on('keydown', '.selector', function (event) {
if (event.which == 13 || event.keyCode == 13) {
//do your thang
}
});
增加来自@Bradley4的更新