I want a live change event in input text element
Solution 1
you can use keyup()
event:
$('#someInput').keyup(function() {
// Your code here
});
there is also an input event:
$('#someInput').on('input', function() {
// Your code here
});
as frnhr pointed out, it's better to use input
event because: "input will handle any change - e.g. if you paste something in the field, input will trigger but keyup wont."
Solution 2
You should use keyUp()
$( "#target" ).keyup(function() {
alert( "Handler for .keyup() called." );
});
Solution 3
You've got three key-related events to choose from, keyup
, keydown
and keypress
; assuming you type the string abc
:
$('#demo').on('keyup', function(e){
console.log(this.value);
});
// a
// ab
// abc
$('#demo').on('keydown', function(e){
console.log(this.value);
});
//
// a
// ab
$('#demo').on('keypress', function(e){
console.log(this.value);
});
//
// a
// ab
The difference is, as the output (roughly) shows, is that keyup
and keypress
respond before the value of the element is updated; so if you want to know the key that was pressed you have to use e.which
(the jQuery normalized keypress event which returns the keyCode
of the pressed-key) in both the keypress
and keyup
handlers and then add that to the value
property. e.which
will, under keyup
also return the correct keyCode
, but you don't have to manually add that key to get the updated value
.
Ramin Omrani
I am a software developer based in Rome, Italy, with a particular focus on the web. I became passionate about programming at the age of 14 when I was a member of the Robocup students' team of Tehran. Since then, my passion for learning new tools and trends in programming has never stopped.
Updated on June 05, 2022Comments
-
Ramin Omrani almost 2 years
I want to handle change event in a text input field. but the event is triggered when the mouse loses focus on element.I want as-type-in change event triggered. what should i do for a live event in jQuery?
I've used :
jQuery('#element').on('change',function(){ //do the stuff });
-
frnhr over 10 years
input
will handle any change - e.g. if you paste something in the field,input
will trigger butkeyup
wont.