开发者

keyup event with wrong input val()

In a script that capture keyup envent I get the wrong value of the input feild.

 $("#country开发者_如何学JAVA-name").keyup(function () {

    if ($(this).val().length > 1 ) {
        console.log($(this).val());
    }
 });

In a input text if I enter b r then I select both letter and enter quickly g r I got one log br but 2 log gr

How can I avoid $(this).val() being update too quickly?

Thanks


The easiest way would be to introduce a delay to account for the person typing.

var t;
$("#country-name").keyup(function() {
    var value = $(this).val();
    clearTimeout(t);
    t = setTimeout(function() {
      if (value.length > 1 ) {
        console.log(value);
      }
    }, 500);
});

Example on jsfiddle


Save it in a local variable like such:

$("#country-name").keyup(function () {
    var value = $(this).val();
    if (value.length > 1 ) {
        console.log(value);
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜