Search code examples
javascriptjquerykeypressjquery-events

jQuery's val() method returns too few characters for keypress event


In my form I add one text box ($("#seltxt")) and one div having text inside. when I select the div text comes in a text box this works fine. Now I added function keypress in the #seltxt in key press event I am copying the textbox text to div. But it getting one less character.

Example:

div having text "manojgangwar" when I am clicking on div ,"manojgangwar" copies to #seltxt. Now suppose I write character "manojgangwar123" in textbox then in div it is only coming "manojgangwar12"

Below is the jQuery to capture keypress event:

 //function to set text to div

$("#seltxt").keypress( function(event) {
   $('#' + objid).text($("input#seltxt").val());
});

Solution

  • The keypress event is fired while a key is pressed, before the default behaviour has occurred. This allows scripts to cancel the default behaviour (e.g. populating an input field) through the event.preventDefault() method.

    Use the keyup event, if you need an event which is fired when the input value has changed.

    Also, since $("input#selText") points to itself, you can also use $(this).val() instead. A further optimisation would consist of using this.value, which is universally supported.

    $("#seltxt").keyup( function(event) {
       $('#' + objid).text(this.value);
    });
    

    A final note on key events

    • keydown - Fired once, right after a key is pressed. Can be used to prevent the first default event.
    • keypress - Fired possibly multiple times, while keys are pressed. Can be used to prevent default behaviour (keydown is fired only once, if you hold key pressed, the default behaviour would occur, unless you define a keypress event)
    • keyup - Fired after the key is released. Using event.preventDefault() cannot prevent text from being modified by keyboard input.