简体   繁体   中英

How to handle multiple buttons enter key functionality?

In my page there are two buttons. For enter key functionality I have written the following jQuery code.

$(function () {    
   $("#first-button-id").keyup(function (e) {
      if (e.keyCode == '13') {
         e.preventDefault();                  
      }
   }).focus();


   $("#second-button-id").keyup(function (e) {
      if (e.keyCode == '13') {              
         e.preventDefault();                 
      }
   }).focus();
});

But always when click on enter key first one is firing. Please tell me how to handle the multiple button enter key functionality.

Try something like this HTML :

<label>TextBox : </label>
<input id="textbox" type="text" size="50" />
<label>TextBox 2: </label>
<input id="textbox2" type="text" size="50" />

JQuery

$('#textbox , #textbox2').keyup(function(event){

    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('You pressed a "enter" key in textbox');  
    }
    event.preventDefault();
}).focus();

DEMO

Some browser prefer keycode and other use which ... I suggest you to use both..

You do not need to focus on two buttons at the same time. Try doing something like this:

$("#button1").keypress(function(event){  
    if ( event.which == 13 ){     
       //Do something}

$("#button2").keypress(function(event){
    if( event.which == 13 ){
        //Do something else}

The problem i think is with your event.preventDefault() function which stops the propogation of the event once a function is executed. In your case, your first function might be getting completed before the second one and hence the second one gets aborted in the middle.

The reason the first submit button is always firing is because that's the default behavior of a web page which you haven't actually altered with your code.

Try this:

$(function () {    
   $("#first-button-id, #second-button-id").keyup(function (e) {
      e.preventDefault();
      e.stopImmediatePropagation();
      if (e.keyCode == '13') {
         $(this).trigger("click");                 
      }
   });
});

What you seem to be asking about strikes me as rather odd. It looks like you want second-button to be 'clicked' if the focus is on second-button and enter is pressed. Tabbing until the focus is on the correct button is really the only practical way this could happen.

$("#first-button-id , #second-button-id ").keyup(function(event){ 
if ( event.which == 13 ) {
     alert("you pressed enter.");
     event.preventDefault(); 
}
}

Try this.

 $('#first-button-id').on("keydown", function (e) { if (e.keyCode == 13) { e.preventDefault(); $("first-button-id").click(); } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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