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.
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));
});
It's also possible that your scanner could simulate a paste
event in the textarea as well;
$('yourTextarea').bind('paste', function () {
var self = $(this);
setTimeout(function () {
alert("Changed to " + self.val());
}, 1);
});
You'll be able to experiment with your scanner to see which method it uses (or implement all of them if you're lazy).
Note that this post was written back in May 2010 when the latest version of jQuery was 1.6.1; since then, bind()
has been replaced in favour of on()
. If you're using a version of jQuery > 1.7, change all occurrences of bind
to on
in the above code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With