RocketNuts
RocketNuts

Reputation: 11110

JQuery on keydown event to focus to a button seems to automatically press the button?

I have two text inputs and a button.

For both text inputs, I set a keydown event with JQuery to switch focus to the next element on pressing Enter.

So:

var counter = 0;
function Foo() 
{
	$('#output').html(++counter); 
}

function FocusToLastName(evt)
{
	var keyCode = evt.keyCode || evt.which; 
  if (keyCode==13) $('#lastname').focus();
}

function FocusToButton(evt)
{
	var keyCode = evt.keyCode || evt.which; 
  if (keyCode==13) $('#btn').focus();
}

$('#firstname').on('keydown',FocusToLastName);
$('#lastname').on('keydown',FocusToButton);
$('#firstname').focus();
#output { color:#0f0; background:#80f; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='firstname' type='text'>
<input id='lastname' type='text'>
<button id='btn' onclick='Foo()'>OK</button>
<h1 id='output'></h1>

To see what happens:

  1. Click on first input field to set focus there.
  2. Press Enter. Focus will move to second input field (correct).
  3. Press Enter again. Focus will move to the button (correct) however the button's onclick event is also triggered (NOT correct)

Note that this only happens when I use the Enter key. If I change the keyCode condition to 40 instead of 13 (for cursor key down instead of Enter) in both event handlers, it works as expected.

Additionally, another small problem: I automatically focus to the first input element which doesn't seem to work. But that may be related to JSFiddle.

Upvotes: 0

Views: 1241

Answers (1)

Bharat Geleda
Bharat Geleda

Reputation: 2780

You need to stop the default event. Use the event.preventDefault() method to do so in your focus to button function like so :

function FocusToButton(evt)
{
    evt.preventDefault();
    var keyCode = evt.keyCode || evt.which; 
    if (keyCode==13) $('#btn').focus();
}

It would be a good idea to add it to other functions as well. Read more on preventDefault() here

Upvotes: 1

Related Questions