There are many ways the value of a <input type="text">
can change, including:
I want my JavaScript function to be called (with the current input value) any time it changes. And I want it to be called right away, not just when the input loses focus.
I'm looking for the cleanest and most robust way to do this across all browsers (using jQuery preferably).
Answer: Use the input Event You can bind the input event to an input text box using on() method to detect any change in it. The following example will display the entered value when you type something inside the input field.
Use input change event to get the changed value in onchange event argument. If you bind using the two-way bind to value property, it will automatically change the value into the value property.
The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.
This jQuery code catches immediate changes to any element, and should work across all browsers:
$('.myElements').each(function() { var elem = $(this); // Save current value of element elem.data('oldVal', elem.val()); // Look for changes in the value elem.bind("propertychange change click keyup input paste", function(event){ // If value has changed... if (elem.data('oldVal') != elem.val()) { // Updated stored value elem.data('oldVal', elem.val()); // Do action .... } }); });
A real-time fancy solution for jQuery >= 1.9
$("#input-id").on("change keyup paste", function(){ dosomething(); })
if you also want to detect "click" event, just:
$("#input-id").on("change keyup paste click", function(){ dosomething(); })
if you're using jQuery <= 1.4, just use live
instead of on
.
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