4

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
});
1
  • What have you tried so far? Can you make a jsfiddle to demonstrate what you're trying to say? Nov 10, 2013 at 18:39

4 Answers 4

17

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."

1
  • 4
    input will handle any change - e.g. if you paste something in the field, input will trigger but keyup wont.
    – frnhr
    Nov 10, 2013 at 18:50
4

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

JS Fiddle demo.

$('#demo').on('keydown', function(e){
    console.log(this.value);
});

// 
// a
// ab

JS Fiddle demo.

$('#demo').on('keypress', function(e){
    console.log(this.value);
});

// 
// a
// ab

JS Fiddle demo.

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.

3

You should use keyUp()

$( "#target" ).keyup(function() {
  alert( "Handler for .keyup() called." );
});
0
0

Since it's 2021, this can be done with "input" as well. But you might need to have a look at Vue.js were it's much easier to accomplish this.

jQuery(document).on('input', '#element', function (e) {
    var input = $(this).val();
    var target = $('.target');
    var fallbackName = target.attr('data-fallback-text'); // Can be handy

    liveInputChange(input, target, fallbackName);
});

function liveInputChange(input, target, fallbackName) {

    if (input === "" || input === null) {
        target.text(fallbackName);
    } else {
        target.text(input);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.