jquery keypress() event get text

59,231

Solution 1

You can try to use the keyup event:

$(selector).keyup(function() {
  var textValue = $(this).val();
  DoX();
});

Solution 2

if you are stuck using the keypressed for some other reason (so you cannot change to keyup as suggested) then you can get the last character typed like this:

$("input[x]").keypress(function (e) {
    var c = String.fromCharCode(e.which);
    //process the single character or
    var textValue = $("input[x]").val();
    var fulltext = textValue + c;
    //process the full text

});

Solution 3

Use onkeyup, it will show the right value.

Share:
59,231
Fiona - myaccessible.website
Author by

Fiona - myaccessible.website

I have a Pluralsight course on web accessibility: Making a Web Form Accessible Web accessibility is more straightforward than you'd think. This course starts with an inaccessible web form and steps through each of the changes necessary to make it accessible, including an introduction to testing with free screen reader software. About Me Director of Software Development at Xibis (web & app development). Blogging about web accessibility at myaccessible.website Please email me at [email protected] or find me on Twitter.

Updated on January 25, 2020

Comments

  • Fiona - myaccessible.website
    Fiona - myaccessible.website over 4 years

    I want a function to be run when a keypress occurs on a text box, so I have this code:

    $("input[x]").keypress(function() {
            DoX();
        })
    

    This is working fine, but in my function I want to do something based on the text value in the textbox

    var textValue = ("input[x]").val();
    

    Now the problem here is that it lags behind by a key so if my text box says 'He' and I type an 'l', then I want my textValue to be 'Hel', but it is returning the previous value 'He' because presumably the character hasn't been put in the text box yet.

    Is there a way of getting 'Hel' out of my function here?

    Thanks :)