JQuery.on () works up to given value

Why does .on () not get the value of the form input field (#forgot) before the key press 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 you enter the first character, the warning does not show the input. The second character causes the value to be only the first character. On () function seems to work before the key is pressed? How can I fix this or is there an alternative function?

+3


source to share


4 answers


Just 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();
        }
    });
});

      

+4


source


keypress

the event fires when a key is pressed. He won't wait for it to come. Try it keyup

. keyup

is triggered when you release the key after pressing, before this time the value will be reached. -

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

      

keystroke



A keypress event is dispatched to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifiers and nonprintable keys such as Shift, Esc, and delete fire key change events but not key press events. Other differences between the two events can occur depending on the platform and browser.

KeyUp

A keyup event is dispatched to an element when the user releases a key from the keyboard. It can be attached to any element, but the event is only dispatched to the element that has focus. The focusable elements can vary between browsers, but form elements can always receive focus, so are reasonable candidates for this type of event.

+6


source


You need a keyup event instead of a keypress.

So, replace:

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

      

FROM

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

      

+1


source


a keypress event is fired when a key is pressed before the key is raised). Thus, he will not receive full 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();
        }
    });
});

      

+1


source







All Articles