JQuery: detect change in input field

487,573

Solution 1

You can bind the 'input' event to the textbox. This would fire every time the input changes, so when you paste something (even with right click), delete and type anything.

$('#myTextbox').on('input', function() {
    // do something
});

If you use the change handler, this will only fire after the user deselects the input box, which may not be what you want.

There is an example of both here: http://jsfiddle.net/6bSX6/

Solution 2

Use jquery change event

Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

An example

$("input[type='text']").change( function() {
  // your code
});

The advantage that .change has over .keypress , .focus , .blur is that .change event will fire only when input has changed

Solution 3

Same functionality i recently achieved using below function.

I wanted to enable SAVE button on edit.

  1. Change event is NOT advisable as it will ONLY be fired if after editing, mouse is clicked somewhere else on the page before clicking SAVE button.
  2. Key Press doesnt handle Backspace, Delete and Paste options.
  3. Key Up handles everything including tab, Shift key.

Hence i wrote below function combining keypress, keyup (for backspace, delete) and paste event for text fields.

Hope it helps you.

function checkAnyFormFieldEdited() {
    /*
     * If any field is edited,then only it will enable Save button
     */
    $(':text').keypress(function(e) { // text written
        enableSaveBtn();
    });

    $(':text').keyup(function(e) {
        if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete key
            enableSaveBtn();
        } else { // rest ignore
            e.preventDefault();
        }
    });
    $(':text').bind('paste', function(e) { // text pasted
        enableSaveBtn();
    });

    $('select').change(function(e) { // select element changed
        enableSaveBtn();
    });

    $(':radio').change(function(e) { // radio changed
        enableSaveBtn();
    });

    $(':password').keypress(function(e) { // password written
        enableSaveBtn();
    });
    $(':password').bind('paste', function(e) { // password pasted
        enableSaveBtn();
    });


}

Solution 4

Use $.on() to bind your chosen event to the input, don't use the shortcuts like $.keydown() etc because as of jQuery 1.7 $.on() is the preferred method to attach event handlers (see here: http://api.jquery.com/on/ and http://api.jquery.com/bind/).

$.keydown() is just a shortcut to $.bind('keydown'), and $.bind() is what $.on() replaces (among others).

To answer your question, as far as I'm aware, unless you need to fire an event on keydown specifically, the change event should do the trick for you.

$('element').on('change', function(){
    console.log('change');
});

To respond to the below comment, the javascript change event is documented here: https://developer.mozilla.org/en-US/docs/Web/Events/change

And here is a working example of the change event working on an input element, using jQuery: http://jsfiddle.net/p1m4xh08/

Solution 5

You can use jQuery change() function

$('input').change(function(){
  //your codes
});

There are examples on how to use it on the API Page: http://api.jquery.com/change/

Share:
487,573

Related videos on Youtube

CL22
Author by

CL22

Updated on January 31, 2020

Comments

  • CL22
    CL22 over 4 years

    I want to detect when a user's keyboard actions alter the value of a text field. It should work consistently across modern browsers.

    The JQuery page for the .keypress event says it's not consistent? Also, it doesn't work for backspace, delete etc.

    I can't use .keydown as it is because it reacts to shift, alt and arrow keys etc. Also, it doesn't fire more than once when the user holds down a key and multiple characters are inserted.

    Is there a concise method I'm missing? Or should I use .keydown and filter out events that are triggered by arrow keys, shift and so on? My main concern is there will be keys that I'm not aware should be filtered. (I nearly forgot about alt and ctrl, I suppose there could be others) But then how would I detect the key being held down and inserting multiple characters?

    As a bonus it would detect changes due to pasting (including right-clicking) but I have the solution to that from here.

  • Joney Spark
    Joney Spark about 11 years
    This does not work in the Nintendo 3DS browser. The change is not detected even though the input field contains the new string.
  • Jason Frank
    Jason Frank over 10 years
    Indeed, keyup seemed to be the only one (not keypress or keydown) that would detect backspace and delete operations, at least in IE 8 and IE 9. Thanks.
  • Daniel
    Daniel almost 10 years
    No 'change' event on input elements
  • totallyNotLizards
    totallyNotLizards almost 10 years
  • totallyNotLizards
    totallyNotLizards almost 10 years
    sorry, second link wrong - see this one for more info: whatwg.org/specs/web-apps/current-work/multipage/…
  • Daniel
    Daniel almost 10 years
    So read again the link and you'll see: "Unlike the input event, the change event is not necessarily fired for each change to an element's value." Which seems what the person posting the question needs
  • totallyNotLizards
    totallyNotLizards almost 10 years
    @Daniel you said that there was no change event, not that it didn't fire every time. That was incorrect, there is a change event. I've read the docs too. Obviously, the selected answer, which advises using the input event, fits the needs of the OP. The selected answer also makes mention of the change event and why it might not be what the OP wants.
  • Daniel
    Daniel almost 10 years
    You are correct!, my 'no event existence' statement is not correct ;).
  • ChristoKiwi
    ChristoKiwi almost 10 years
    Note for textfields this only is detected onblur
  • Shawn J. Molloy
    Shawn J. Molloy over 9 years
    @Gatada I'm glad my employer does not make me verify web code for the Nintendo 3DS browser.
  • jarvan
    jarvan almost 8 years
    does it work with select dropdowns?
  • Edd
    Edd over 5 years
    @Daniel & totallyNotLizards that is not how I read it... Sounded like Daniel was saying "don't use change" on inputs for this scenario.
  • Sliq
    Sliq almost 5 years
    this will fail for input fields that are generated AFTER initial page load, like the popular select2 plugin
  • mtronics
    mtronics almost 5 years
    @Sliq Can be fixed by changing it to $(document).on("input", "#myTextbox", function() {...}). This will trigger for all runtime-generated inputs with this ID.
  • Houy Narun
    Houy Narun over 3 years
    @Timm, will this work, if I set value of input #myTextbox via Jquery, like `$('#myTexbox').val('some_value') ? Thanks