-1

is it possible to bind an event handler to an input field that will be fired, as soon as the value changes although it is not focused?

Thank you.

OOPDeveloper89
  • 207
  • 5
  • 18

2 Answers2

0

From the Jquery official documentation :

The change event is sent to an element when its value changes. This event is limited to elements, boxes and elements.

So you could easily do something like this in Jquery:

$( "#bar" ).change(function() {
   alert( "Handler for .change() called." );
});

You don't have such a functionality available in pure javascript. In that case you could, simply define a function that checks the value of your input and do that periodically using a setInterval method (from a relvant SO Post):

  var foo = document.getElementById("bar");
  var oldValue = foo.value;

  function checkIfValueChanged() {
    if(foo.value != oldValue) {
       //necessary code trigerred on value change
       clearInterval(checker);
  }
  }

 //every 500ms check if value changed
 var checker = setInterval('checkIfValueChanged()', 500);

I hope this gets you started in the right direction.

Community
  • 1
  • 1
Vivek Pradhan
  • 4,777
  • 3
  • 26
  • 46
0

Yes it's possible but there isn't a native event handler. The change event handler works when the value in the field has lost focus and the value has changed (I think).

As Vivek has pointed out, what you'd need is some code that will fire when the value contained in the form element changes.

If this is changing through some other means than user interaction then you might want to consider looking at the trigger rather than trying to write an event handler of sorts, consider watching the value that populates the form field rather than the form field itself, via simple pub / sub mechanism.

Lewis
  • 5,769
  • 6
  • 30
  • 40