jQuery change input value on keyup

Check if input value was changed on keyup immediately (with jQuery):

$(function(){
    $('form input').data('val',  $('form input').val() ); // save value
    $('form input').change(function() { // works when input will be blured and the value was changed
        // console.log('input value changed');
        $('.log').append(' change');
    });
    $('form input').keyup(function() { // works immediately when user press button inside of the input
        if( $('form input').val() != $('form input').data('val') ){ // check if value changed
            $('form input').data('val',  $('form input').val() ); // save new value
            $(this).change(); // simulate "change" event
        }
    });
});
<form>
    <input type="text" placeholder="type here to test events...">
    <div class="log">log of change and keyup events. </div>
</form>

Also check how to remove text in input on focus.

4 comments on “jQuery change input value on keyup

  1. it doesn't work. When I enter some text and then press arrow buttons it will write that text changed but it is false.

    1. web-developer

      Yes, you're right, code triggers only for keyup actions.
      You may re-write your code by remembering prev string in text input and comparing it with current.
      If these strings are different, you may trigger your custom action.

    2. webster

      I re-write the code and now old input value is checked if it is changed.

Leave a Reply

Your email address will not be published. Required fields are marked *