jquery keypress() event get text

前端 未结 4 1106
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 03:42

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();
    })
相关标签:
4条回答
  • 2021-02-05 04:00

    Use onkeyup, it will show the right value.

    0 讨论(0)
  • 2021-02-05 04:02

    You can try to use the keyup event:

    $(selector).keyup(function() {
      var textValue = $(this).val();
      DoX();
    });
    
    0 讨论(0)
  • 2021-02-05 04:03

    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
    
    });
    
    0 讨论(0)
  • 2021-02-05 04:10

    Use setTimeout without a delay. It will run immediately after keypress event completes so you'll have the correct value of the input.

    $("input[x]").keypress(function() {
      setTimeout(DoX);
    });
    
    0 讨论(0)
提交回复
热议问题