3

Why does .on() not get the value of the form input field (#forgot) before the keypress has happened.

$(document).ready(function() {
    $(document).on('keypress', '#pass', function() {
    var value = $.trim($('#pass').val());
        alert(value);
        if (!value.length) {
            alert("Show");
            $('#forgot').show();
        } else {
            alert("Hide");
            $('#forgot').hide();
        }
    });
});

When I type in the first character the alert shows no input. The second character leads to the value being only the first character. The .on() function seems to run before the key press is registered? How can I fix this or is there an alternative function?

Enayet Hussain
  • 908
  • 4
  • 17
  • 33

4 Answers4

6

keypress event triggered when you press a key. It will not wait for the value to come. Try with keyup. keyup gets triggered when you a key is released after pressing, till that time the value is proccessed. -

 $(document).on('keyup', '#pass', function() {

keypress

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.

keyup

The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

Legionar
  • 7,472
  • 2
  • 41
  • 70
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
4

Simply change keypress to keyup:

$(document).ready(function() {
    $(document).on('keyup', '#pass', function() {
    var value = $.trim($('#pass').val());
        console.log(value);
        if (!value.length) {
            console.log("Show");
            $('#forgot').show();
        } else {
            console.log("Hide");
            $('#forgot').hide();
        }
    });
});
Legionar
  • 7,472
  • 2
  • 41
  • 70
1

You need the keyup event instead of the keypress.

So replace:

 $(document).on('keypress', '#pass', function() {

With

 $(document).on('keyup', '#pass', function() {
Bas Slagter
  • 9,831
  • 7
  • 47
  • 78
1

keypress event is triggered when the key is pressed before the key is up). So it won't get the complete value. Use keyup

JSFIDDLE DEMO

HTML

<input id="pass">

JQUERY

$(document).ready(function() {
    $(document).on('keyup', '#pass', function() {
    var value = $.trim($('#pass').val());
        alert(value);
        if (!value.length) {
            alert("Show");
            $('#forgot').show();
        } else {
            alert("Hide");
            $('#forgot').hide();
        }
    });
});
Coder
  • 6,948
  • 13
  • 56
  • 86