I want a live change event in input text element

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
});

8 thoughts on “I want a live change event in input text element”

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

    Reply
  2. 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);
        }
    }
    
    Reply
  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
    

    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.

    Reply

Leave a Comment