views:

209

answers:

3

How do I set up a listener in jQuery/javascript to monitor a if a value in the textbox has changed? The value is fed into the textbox by a bar code scanner attached to the tablet,so each time an item is scanned the value in the textbox changes.I need to display some information based on the value in the textbox.

+3  A: 

How about:

$('#textbox').change(function()
{
    alert($(this).val());
});
nc3b
+2  A: 

It depends how your scanner inputs the value, and what the scanner software does after inputting the value.

If the scanner takes the focus off the textarea after inputting the value, you can do:

$('yourTextarea').bind('change', function () {
    alert("Changed to " + $(this).val());
});

If it doesn't take off focus, you'll have to monitor the keypresses, and react after a period of inactivity.

$('yourTextarea').bind('keypress', function () {
    var self = $(this);

    clearTimeout(self.data('timeout'));

    self.data('timeout', setTimeout(function() {
        alert("Changed to " + $(this).val());
    }, 500));
});
Matt
@matt dude thanks,but how come its not wrking when i paste values in it?
manraj82
to be complete, you'll want to monitor mouse events as the user can right-click and paste as well (not to mention drag-n-drop text in the box.
scunliffe
+1  A: 

The reality is that the 'change' event in jQuery is not always viable across all browsers, some of the older ones don't treat the event properly. I've had this problem on a number of projects and typically what needs to happen is to bind to a few properties of a textarea to capture user interaction. If it is an input area of the text type it can be simpler, but usually you will need to cover your bases with a few event listeners.

I would take a look at how some people who are doing character counters write their code for listening to a textarea's values and then also set up your code to

Try to cover your bases and maybe try something like this:

$('#textareatextID').bind('keyup click blur focus change paste', function() {
    alert($(this).val());
});

This also keeps you form having to set timers, and since I don't know the method that the barcode scanner is using to change the value of the textarea my recommendation is a pretty broad one.

Liam