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?
This question is related to
javascript
jquery
html
This covers every change to an input using jQuery 1.7 and above:
$(".inputElement").on("input", null, null, callbackFunction);
If you want the event to be fired whenever something is changed within the element then you could use the keyup event.
If you've got HTML5:
oninput
(fires only when a change actually happens, but does so immediately)Otherwise you need to check for all these events which might indicate a change to the input element's value:
onchange
onkeyup
(not keydown
or keypress
as the input's value won't have the new keystroke in it yet)onpaste
(when supported)and maybe:
onmouseup
(I'm not sure about this one)With HTML5 and without using jQuery, you can using the input
event:
var input = document.querySelector('input');
input.addEventListener('input', function()
{
console.log('input changed to: ', input.value);
});
This will fire each time the input's text changes.
Supported in IE9+ and other browsers.
Try it live in a jsFiddle here.
There are jQuery events like keyup and keypress which you can use with input HTML Elements. You could additionally use the blur() event.
// .blur is triggered when element loses focus
$('#target').blur(function() {
alert($(this).val());
});
// To trigger manually use:
$('#target').blur();
As others already suggested, the solution in your case is to sniff multiple events.
Plugins doing this job often listen for the following events:
$input.on('change keydown keypress keyup mousedown click mouseup', handler);
If you think it may fit, you can add focus
, blur
and other events too.
I suggest not to exceed in the events to listen, as it loads in the browser memory further procedures to execute according to the user's behaviour.
Attention: note that changing the value of an input element with JavaScript (e.g. through the jQuery .val()
method) won't fire any of the events above.
(Reference: https://api.jquery.com/change/).
Source: Stackoverflow.com