Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does focus trigger a keyup event?

I made 3 input boxes for time input (hh, mm, ss) When the user type in 2 digits in hh, it will automatically focus the next (mm) field. Same for mm and ss.

I am using the 'keyup' event to bind my input boxes. However the behaviour is strange:

If I type 2 digits SLOWLY, it works. If I type FASTER, it will jump twice.

I suspect the 'focus' event triggers the keyup event, and I dont know how to deal with it. I have tried to .preventDefault on the focus event. But no luck.

Here is the code:

$('#hh').on('keyup', function (e) {
    var hh = $('#hh').val().toString();
    if (hh.length >= 2) {
        $('#mm').focus();
    }
});

$('#mm').on('keyup', function (e) {
    var mm = $('#mm').val().toString();
    if (mm.length >= 2) {
        $('#ss').focus();
    }
});

Here is a demo:

jsfiddle (http://jsfiddle.net/ch3ksuwa)

To reproduce: type in 2 digits quickly in hh field, and it will jump to ss instead of mm

I tried on Chrome and Firefox, same issue

like image 940
hello_harry Avatar asked Mar 02 '26 23:03

hello_harry


1 Answers

It looks like $('#hh').val() is happening after the second key press but I'm not sure why the second 'keyup' event's target is #mm.

You could try using the 'input' event instead of the 'keyup' event. This event triggers when the input's value is changing. It is more semantic for this purpose and avoids any problems with keyboard events firing at the wrong time.

$('#hh').on('input', function (e) {
  var hh = $('#hh').val().toString();
  if (hh.length >= 2) {
    $('#mm').focus();
  }
});

$('#mm').on('input', function (e) {
  var mm = $('#mm').val().toString();
  if (mm.length >= 2) {
    $('#ss').focus();
  }
});

I haven't checked which browsers support this yet. It's working on Chrome for me.

like image 94
zmln Avatar answered Mar 05 '26 13:03

zmln



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!