Eduardo Ponce de Leon
Eduardo Ponce de Leon

Reputation: 9706

How to detect when the value of an input changes dynamically with JS / Jquery

I am able to detect if an input changes value while typing, pasting, etc, But if the value changed dynamically from another script I am unable to detect it:

Lets say I have an input

<input id="testInput" value="Type Here" />

And if the value changes by typing on it I want to alert "changed"

$('#testInput').on('input', function(){
    alert("changed");
});

This works, but if the value changed dynamically from another script, I can't trigger the alert:

$('#testInput').val("Dynamic Value"); //This doesn't show the alert

I want to be able to detect if the value changed at all, either by typing, pasting, or dynamically from a script or action.

.val() Is beeing executed in many different places, so changing .val() all over the code for something else like .val().trigger("change") is not an option.

Here is a jsfiddle with a better example:

https://jsfiddle.net/xpvt214o/486146/

Upvotes: 3

Views: 9614

Answers (3)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33943

Inpired of Ele's answer...

While overriding the .val() function... Instead of comparing the id, you could add an agrument for the even to trigger! If it's not provided, there is no change from the "regular" .val() function. If provided, it triggers the event.

You will have to change every places where the value is programmatically changed anyway, but in a more practical way. ;)

var $val = $.fn.val;
$.fn.val = function(newVal,eventToTrigger) {
  if (eventToTrigger != null) this.trigger(eventToTrigger);
  $val.call(this, newVal);
}

$('.someClass').on('input', function() {
  alert("Programmatically inputted!");
});

$('.otherClass').on('change', function() {
  alert("Programmatically changed!");
});

$('.someClass').val('Hello you!','input');
$('.otherClass').val('Doing fine?','change');
$('#whatever').val('Hehehe.');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" class="someClass">
<input type="text" class="otherClass">
<input type="text" id="whatever">

Upvotes: 2

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33943

Just trigger the event!

$('#testInput').val("Dynamic Value").trigger("input");

Upvotes: 4

Ele
Ele

Reputation: 33736

An alternative is overriding the function $.fn.val()

This is a basic approach to start with.

var $val = $.fn.val;
$.fn.val = function(newVal) {
  if (this.attr('id') === 'target') this.trigger('input');
  $val.call(this, newVal);
}

$('#target').on('input', function() {
  alert("changed");
});

$('#target').val('Ele from Stack');
$('#target2').val('Ele from Stack2');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id='target' />
<input id='target2' />

Upvotes: 1

Related Questions