简体   繁体   English

如何将Enter键限制为只有两个提交按钮的表单中的一个按钮

[英]How to limit enter key press to only one button in a form having two submit buttons

I have an HTML form having two submit type input buttons with different actions attached. 我有一个HTML form ,其中包含两个带有不同操作的提交类型输入按钮。 The form should get submitted on click of any of these buttons. 单击这些按钮中的任何一个,即可提交表单。 But on enter key press , button-B should trigger the submit. 但是在按Enter键时按钮B应该触发提交。 Now as i have button-A on top of button-B in the order, button-A is getting triggered on enter press. 现在,当我顺序将按钮-A放在按钮-B的顶部时,在按下Enter键时会触发按钮-A

Please note that changing the order of buttons is not possible in my case. 请注意,在我的情况下无法更改按钮的顺序。

My code goes like this, 我的代码是这样的,

<form method="POST" action="someAction">
  <input type="text" name="fName"/>
  <input type="text" name="lName"/>
  <input type="submit" value="Action-A" name="button-A"/>
  <input type="submit" value="Action-B" name="button-B"/>
</form>

You can add listeners to all inputs and when the user hit enter you can prevent the default action by using e.preventDefault() . 您可以将侦听器添加到所有输入,当用户按下Enter键时,可以使用e.preventDefault()阻止默认操作。 Then select the second submit button and click it. 然后选择第二个提交按钮并单击它。

<script>
window.onload = function() {
    //Select all of input in #form1 of type text
    var inputs = document.querySelectorAll("#form1 > input[type=text]");
    for(var i = 0; i < inputs.length; i++) {
        //Add listeners
        inputs[i].addEventListener("keypress", function(e) {
            var key = e.which || e.keyCode;
            //Check if enter is pressed
            if(key == 13) {
                //Prevent from submitting with A
                e.preventDefault();
                //Click B
                document.getElementById('b').click();
            }
        }, false);
    }
}
</script>

<form id="form1" method="POST" action="someAction">
<input type="text" name="fName"/>
<input type="text" name="lName"/>
<input type="submit" value="Action-A" name="button-A"/>
<input type="submit" value="Action-B" id="b" name="button-B"/>
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM