When using jquery .change
on an input
the event will only be fired when the input loses focus
In my case, I need to make a call to the service (check if value is valid) as soon as the input value is changed. How could I accomplish this?
Approach 2: There are few other events that can be used to detect the change in content of textbox. Use any or all of them onchange event, onpropertychange event, onkeyup event, onpaste event and oninput event in the input element and call a function to see the effect.
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.
UPDATED for clarification and example
examples: http://jsfiddle.net/pxfunc/5kpeJ/
Method 1. input
event
In modern browsers use the input
event. This event will fire when the user is typing into a text field, pasting, undoing, basically anytime the value changed from one value to another.
In jQuery do that like this
$('#someInput').bind('input', function() { $(this).val() // get the current value of the input field. });
starting with jQuery 1.7, replace bind
with on
:
$('#someInput').on('input', function() { $(this).val() // get the current value of the input field. });
Method 2. keyup
event
For older browsers use the keyup
event (this will fire once a key on the keyboard has been released, this event can give a sort of false positive because when "w" is released the input value is changed and the keyup
event fires, but also when the "shift" key is released the keyup
event fires but no change has been made to the input.). Also this method doesn't fire if the user right-clicks and pastes from the context menu:
$('#someInput').keyup(function() { $(this).val() // get the current value of the input field. });
Method 3. Timer (setInterval
or setTimeout
)
To get around the limitations of keyup
you can set a timer to periodically check the value of the input to determine a change in value. You can use setInterval
or setTimeout
to do this timer check. See the marked answer on this SO question: jQuery textbox change event or see the fiddle for a working example using focus
and blur
events to start and stop the timer for a specific input field
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