Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

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

  • keypresses
  • copy/paste
  • modified with JavaScript
  • auto-completed by the 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).

Example use case: On the Twitter Signup page, the username field's value gets shown in the url "http://twitter/usernamebelow it.

1 Answer

0 votes
by (40.7k points)

This jQuery code is used to catch the immediate changes to any element, you can use this for all browsers like this:

 $('.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

       ....

     }

   });

 });

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...