Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect all changes to a <input type="text"> (immediately) using JQuery

There are many ways the value of a <input type="text"> can change, including:

  • keypresses
  • copy/paste
  • modified with JavaScript
  • auto-completed by browser or a toolbar

I want my JavaScript function to be called (with the current input value) any time it changes. And I want it to be called right away, not just when the input loses focus.

I'm looking for the cleanest and most robust way to do this across all browsers (using jQuery preferably).

like image 770
Dustin Boswell Avatar asked Dec 22 '09 18:12

Dustin Boswell


People also ask

How do you detect change in text input box?

Answer: Use the input Event You can bind the input event to an input text box using on() method to detect any change in it. The following example will display the entered value when you type something inside the input field.

How do you find the input value of change?

Use input change event to get the changed value in onchange event argument. If you bind using the two-way bind to value property, it will automatically change the value into the value property.

What does .change do in jQuery?

The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.


2 Answers

This jQuery code catches immediate changes to any element, and should work across all browsers:

 $('.myElements').each(function() {    var elem = $(this);     // Save current value of element    elem.data('oldVal', elem.val());     // Look for changes in the value    elem.bind("propertychange change click keyup input paste", function(event){       // If value has changed...       if (elem.data('oldVal') != elem.val()) {        // Updated stored value        elem.data('oldVal', elem.val());         // Do action        ....      }    });  }); 
like image 56
phatmann Avatar answered Oct 03 '22 18:10

phatmann


A real-time fancy solution for jQuery >= 1.9

$("#input-id").on("change keyup paste", function(){     dosomething(); }) 

if you also want to detect "click" event, just:

$("#input-id").on("change keyup paste click", function(){     dosomething(); }) 

if you're using jQuery <= 1.4, just use live instead of on.

like image 43
Felix Avatar answered Oct 03 '22 18:10

Felix