1
$("#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?

Tural Ali
  • 22,202
  • 18
  • 80
  • 129

1 Answers1

1

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
Community
  • 1
  • 1
styfle
  • 22,361
  • 27
  • 86
  • 128
  • I think change only fires when the element loses focus, not worked. I need something that changes value directly after input – Tural Ali Feb 01 '12 at 03:15
  • I updated my answer. There is another question that is very simliar to this one: http://stackoverflow.com/questions/6771140/jquery-text-change-event – styfle Feb 01 '12 at 03:33
  • the problem is, this script has problem. for ex `1,2,` counts like 3. How to fix that problem? – Tural Ali Feb 01 '12 at 03:45
  • @trl13 `$(this).val().replace(" ", "").replace(/[\s,]+$/, '');` – Cheery Feb 01 '12 at 03:49
  • @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 Feb 01 '12 at 03:58