jQuery get input value after keypress

后端 未结 9 1502
野趣味
野趣味 2020-11-28 21:40

I have the following function:

$(document).ready(function() {
    $(\"#dSuggest\").keypress(function() {
        var dInput = $(\'input:text[name=dSuggest]\'         


        
相关标签:
9条回答
  • 2020-11-28 22:07

    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");
    });
    
    0 讨论(0)
  • 2020-11-28 22:11

    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.

    0 讨论(0)
  • 2020-11-28 22:13

    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)
    });
    
    0 讨论(0)
提交回复
热议问题