La función de contador de palabras no funciona con el escáner de código de barras

$("#itemids").keypress(function(){
    var value = $(this).val().replace(" ", "");
    var words = value.split(",");
    $("#counter").html(words.length);
}); 

This function works well with keyboard. But when I use barcode scanner, (I'm just focusing cursor on textarea and it starts to scan barcode into textarea by delimiters like comma.) it doesn't work at all.

I think it must be something other than keypress(function() . Because bc scanner enters words programmatically. How to get it work for both situations: keyboard and bc scanner?

preguntado el 01 de febrero de 12 a las 03:02

Does the scanner really 'enters' words one by one or just 'pastes' the whole string? -

has probado el input ¿evento? help.dottoro.com/ljhxklln.php -

1 Respuestas

It looks like the solution is to use polling, not events.

function update(){
    var value = $("#itemids").val().replace(" ", "");
    var words = value.split(",");
    $("#counter").html(words.length);
}

setInterval(update, 10); // poll every 10ms

contestado el 23 de mayo de 17 a las 14:05

I think change only fires when the element loses focus, not worked. I need something that changes value directly after input - Tural Ali

I updated my answer. There is another question that is very simliar to this one: stackoverflow.com/questions/6771140/jquery-text-change-event - styfle

the problem is, this script has problem. for ex 1,2, counts like 3. How to fix that problem? - Tural Ali

@trl13 $(this).val().replace(" ", "").replace(/[\s,]+$/, ''); - Alegre

@trl13: You could check if the last char is ',' and remove it if it is. Then call split. Or call split first and check if the last element is an empty string. Then remove it. - styfle

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.