jquery keypress() event get text

拜拜、爱过 提交于 2019-12-03 10:40:39

问题


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();
    })

This is working fine, but in my function I want to do something based on the text value in the textbox

var textValue = ("input[x]").val();

Now the problem here is that it lags behind by a key so if my text box says 'He' and I type an 'l', then I want my textValue to be 'Hel', but it is returning the previous value 'He' because presumably the character hasn't been put in the text box yet.

Is there a way of getting 'Hel' out of my function here?

Thanks :)


回答1:


You can try to use the keyup event:

$(selector).keyup(function() {
  var textValue = $(this).val();
  DoX();
});



回答2:


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

});



回答3:


Use onkeyup, it will show the right value.




回答4:


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);
});


来源:https://stackoverflow.com/questions/1411557/jquery-keypress-event-get-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!