148

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Or Weinberger
  • 7,332
  • 23
  • 71
  • 116

10 Answers10

223

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

Frederik
  • 2,777
  • 1
  • 20
  • 26
  • 30
    This should be marked as a proper answer - keyup maybe solves missing character problem, but is problematic to determine if character was actually written (and the key wasn't for example "tab" or "home"). +1 for you – Nashi Mar 28 '14 at 13:23
  • The problem is that it not is supported in old browsers and IE9 don't respond to deleted characters. – PhoneixS Feb 15 '17 at 11:13
174

This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). You should use keyup instead, which is fired after the character has been added.

Note that, if your element #dSuggest is the same as input:text[name=dSuggest] you can simplify this code considerably (and if it isn't, having an element with a name that is the same as the id of another element is not a good idea).

$('#dSuggest').keypress(function() {
    var dInput = this.value;
    console.log(dInput);
    $(".dDimension:contains('" + dInput + "')").css("display","block");
});
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 2
    Works, but with jquery 2.x out this is out of date now as the answer below using the on and input is the best way to do it now. – Piotr Kula Jul 16 '14 at 16:14
  • 2
    @ppumkin: Just because jQuery 2 is out, doesn't mean people don't need to support IE8 and lower. And I don't see anything in the docs that suggests actual support for the `input` event type. – cookie monster Aug 14 '14 at 22:21
  • 7
    You correct, they should stop supporting IE, point. Most "workarounds" in jQuery 1.x are for IE, so it should really be renamed to jQuerIE. – Piotr Kula Aug 15 '14 at 20:26
37

Use .keyup instead of keypress.

Also use $(this).val() or just this.value to access the current input value.

DEMO here

Info about .keypress from jQuery docs,

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character. In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • 6
    `keyup` is too slow, and a key can be pressed and held without being released and things must happen. better to use `keydown` with a little timeout so the value actually changes. – vsync Feb 26 '13 at 22:12
  • the only downside I've found is that if the user pressed more than one keyboard character together, it will not register correctly. – vsync Feb 26 '13 at 22:18
6

I was looking for a ES6 example (so it could pass my linter) So for other people who are looking for the same:

$('#dSuggest').keyup((e) => {
    console.log(e.currentTarget.value);
});

I would also use keyup because you get the current value that is filled in.

MarvinVK
  • 2,964
  • 1
  • 22
  • 21
5

You have to interrupt the execution thread to allow the input to update.

  $(document).ready(function(event) {
       $("#dSuggest").keypress(function() {
           //Interrupt the execution thread to allow input to update
               setTimeout(function() {
                   var dInput = $('input:text[name=dSuggest]').val();
                   console.log(dInput);
                   $(".dDimension:contains('" + dInput + "')").css("display","block");
               }, 0);
       });
  });
parliament
  • 21,544
  • 38
  • 148
  • 238
4

This is because Keypress event is fired before the new character is added. Use 'keyup' event instead,which will work perfectly in your situation.

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

I want to add to this, if you have many textboxes and you have to do the same thing on their keyup event you can simply give them a common css class(eg commoncss) and apply keyup event like this.

$(document).ready(function() {
    $(".commoncss").keyup(function() {
        //your code
    });
});

this will greatly reduce you code as you don't have to apply keyup event by id for each textboxes.

Gowri
  • 1,832
  • 3
  • 29
  • 53
yogihosting
  • 5,494
  • 8
  • 47
  • 80
1

I think what you need is the below prototype

$(element).on('input',function(){code})
Rohan Khude
  • 4,455
  • 5
  • 49
  • 47
apexpals.com
  • 305
  • 1
  • 11
1

Just use a timeout to make your call; the timeout will be called when the event stack is finished (i.e. after the default event is called)

$("body").on('keydown', 'input[type=tel]', function (e) {
    setTimeout(() => {
        formatPhone(e)
    }, 0)
});
Smonge
  • 21
  • 4
0

please use this code for input text

$('#search').on("input",function (e) {});

if you use .on("change",function (e) {}); then you need to blur input

if you use .on("keyup",function (e) {}); then you get value before the last character you typed

keivan kashani
  • 1,263
  • 14
  • 15
0
 $(document).on('keypress',((e)=>{
 console.log(e.which)
 }))

I read the JQuery Documentation (7th June 2023) and it used (e.which) and it returned the ASCII value of the key pressed. Hope it helps.