jgwl
jgwl

Reputation: 327

Why is my enter key cascading via $.focus()?

If I have a textbox and a button:

<input id='text'/> <button id='btn'>Click me</button>

And my button sends focus to the text box somewhere in it's click event:

$(document).ready(function(){

  $('#btn').click(function(event){
    console.log('btn ');
    $('#text').focus();
  });

  $('#text').keyup(function(event){
    console.log('key ');
  });

});

...if you use the enter key to trigger the button click, somehow, the text element that is receiving focus also receives the enter keypress.

Here is a fiddle showing this behavior:

https://jsfiddle.net/qup6keLd/

Use the tab key to set focus to the button, then press the Enter key. Both events will be triggered. Using space to trigger the button's click won't do this. Why is this happening, and how do I prevent it (outside of removing the focus() call?)

Upvotes: 1

Views: 53

Answers (1)

atul
atul

Reputation: 562

Use keypress event instead of keyup event.

The jQuery documentation details the differences between the two.

See the updated fiddle:

$(document).ready(function(){
    $('#text').keypress(function(event){
    $('#output').append('key ');
  });
  $('#btn').click(function(event){
    $('#text').focus();
    $('#output').append('btn ');
  });
});

Updated Fiddle

Upvotes: 1

Related Questions