tirenweb
tirenweb

Reputation: 31709

How to detect changes in the value of an input text, when the value is modified by another event

I'm wondering how to detect changes in the value of an input text, when the value is modified by another event.

$('input').on('change', function() {
  //I expected this below to be shown when pressing '+'
 alert("You changed the value of the input");   
})

$('span').on('click', function() {
    $('input').val('1');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input  type="text" value="0">
<span>+</span>

Upvotes: 1

Views: 51

Answers (2)

redbirdo
redbirdo

Reputation: 4957

From the JQuery onChange documentation (equivalent to on('change', ...)):

Note: Changing the value of an input element using JavaScript, using .val() for example, won't fire the event.

However, you can trigger a change event yourself after updating the field:

$('span').on('click', function() {
    $('input').val('1').change();
})

Upvotes: 1

Barry Tormey
Barry Tormey

Reputation: 3126

It may seem dirty, but you could just set up an interval to check the value.

var inputValue = $('input').val();
setInterval(function () {
    if($('input').val() != inputValue) {
        alert("Changed");
    }
},100);

The only other option you have is to move the alert event into the method that is causing the value change, in this case the click on the plus.

Upvotes: 0

Related Questions