2014-08-28 85 views
0

我有一个HTML form有两个提交类型输入按钮与不同的动作连接。表单应该在点击任何这些按钮时提交。但是在输入按键,button-B应该会触发提交。现在,因为我有button-A之上button-B in order,button-A正在触发输入按下。如何限制回车键只有一个按钮在一个窗体中有两个提交按钮

请注意,在我的情况下,不能更改按钮的顺序。

我的代码是这样的,

<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> 
+0

是否有真正的理由在一个表单中有两个提交按钮? – hindmost 2014-08-28 10:20:59

+0

@最后实际上这些按钮在jsp中附有两个不同的处理程序 – 2014-08-28 10:24:06

回答

0

您可以添加侦听所有的输入和当用户按下回车键,你可以通过使用e.preventDefault()防止默认动作。然后选择第二个提交按钮并单击它。

<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>