jQuery get input value after keypress

Or Weinberger picture Or Weinberger · Jan 9, 2012 · Viewed 259.3k times · Source

I have the following function:

$(document).ready(function() {
    $("#dSuggest").keypress(function() {
        var dInput = $('input:text[name=dSuggest]').val();
        console.log(dInput);
        $(".dDimension:contains('" + dInput + "')").css("display","block");
    });
});

For some reason, for the first keypress, I'm getting an empty string to the console log.

Answer

Frederik picture Frederik · Oct 16, 2013

Realizing that this is a rather old post, I'll provide an answer anyway as I was struggling with the same problem.

You should use the "input" event instead, and register with the .on method. This is fast - without the lag of keyup and solves the missing latest keypress problem you describe.

$('#dSuggest').on("input", function() {
    var dInput = this.value;
    console.log(dInput);
    $(".dDimension:contains('" + dInput + "')").css("display","block");
});

Demo here