键入 HTML 输入类型文本的更改事件对我的情况不起作用

key up and on change event for an html input type text not working for my case

本文关键字:事件 我的 情况 不起作用 输入 HTML 类型 文本 键入      更新时间:2023-09-26

我有一个html输入作为,

<input type="text" id="txtCheckoutBCode" name="barcode" class="sfInputbox" />

现在我想触发一些ajax调用,同时条形码阅读器读取条形码,条形码反映在上面的文本字段中。

我尝试了以下代码,

$('#txtCheckoutBCode').on('change', function() {
    var me= $(this);
    var number = 0;
    number = $.trim(me.val());                        
    if (number.length == 12) { // 12 coz my barcode is of length 12
        //ajaxcall method
    }
});

但仅当焦点从输入字段更改时才会触发。也

 $('#txtCheckoutBCode').on('keyup', function() {
     var me= $(this);
     var number = 0;
     number = $.trim(me.val());                        
     if (number.length == 12) { //12 coz my barcode is of length 12
         //ajax call method
     }
 });

这会触发两次 ajax 调用,我不喜欢这样。

一旦输入字段充满条形码,我需要立即调用 ajax 代码。但不是两次。

首先,

您应该使用 propertychange keyup input paste 而不是 keyup,以确保检测到与您的输入的任何交互(例如粘贴)。但它可能会触发该事件两次,尤其是在 Firefox 中。我建议只使用keyup paste

change ,正如您所说,当输入失去焦点时将被触发。 每次按键都会触发keyup

如果希望 ajax 调用只执行一次,请尝试使用 stopImmediatePropagation():

$('#txtCheckoutBCode').on('keyup paste', function(e) {
    e.stopImmediatePropagation();
    var me= $(this);
    var number = 0;
    number = $.trim(me.val());                        
    if (number.length == 12) { // 12 coz my barcode is of length 12
        //ajaxcall method
    }
});

http://jsfiddle.net/fC5yh/

将按键更改为按键

<script type="text/javascript" >
$(function() {            
$('#txtCheckoutBCode').on('keypress', function() {
                var self = $(this);
                var number = 0;
                number = $.trim(self.val());                        
                    if (number.length == 12) { //12 coz my barcode is of length 12
                        //ajax call method              
                    }
            });
});
</script>                       
<input type="text" id="txtCheckoutBCode" name="barcode" class="sfInputbox" />