我有一个带有两个文本框的表单,一个选择下拉框和一个单选按钮。当按下enter键时,我想调用JavaScript函数,但当我按下它时,表单就提交了。

当按下回车键时,如何防止表单被提交?


当前回答

重写表单的onsubmit动作,调用你的函数,并在后面添加return false,即:

<form onsubmit="javascript:myfunc();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">

在我看来,一个更简单有效的方法应该是:

function onPress_ENTER()
{
        var keyPressed = event.keyCode || event.which;

        //if ENTER is pressed
        if(keyPressed==13)
        {
            alert('enter pressed');
            keyPressed=null;
        }
        else
        {
            return false;
        }
}

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();
});

最好能有一个更通用的版本,可以触发所有延迟事件,而不仅仅是表单提交。

如果你正在使用jQuery:

$('input[type=text]').on('keydown', function(e) {
    if (e.which == 13) {
        e.preventDefault();
    }
});

使用两个事件。which和event.keyCode:

function (event) {
    if (event.which == 13 || event.keyCode == 13) {
        //code to execute here
        return false;
    }
    return true;
};