47

I have the following jQuery code in place on my page:

var isChanged = false;
$(document).ready(function()
{
    $('.change').change(function() {
        isChanged = true;
    });
});

I am using a plugic that modifies the value of the text box it is linked to using:

target.val('xxxx');

the text box in the html (from asp.net) is:

<input name="ctl00$cphHolder1$rptFlex$ctl01$txtLeftRank"
  type="text"
  value="52°"
  id="ctl00_cphHolder1_rptFlex_ctl01_txtLeftRank"
  class="change atiselector" />

When the value of the text box is changed using code, the change is not firing. If I type in the text box, the change fires. What am I missing?

4 Answers 4

78

That's the way it works. If you need the change of value to trigger the "change" event, you can explicitly do so by:

$('input#whatever').val('hi').change();
Sign up to request clarification or add additional context in comments.

2 Comments

One of the stupidest things ever. Tempted to patch val() to make it behave sensibly
@AndrewBullock and if you implemented this "sensible" patch, you wouldl likely discover it significantly degrades your app's performance.
4

$('.change').change() will fire the event. Just changing the attributes doesn't fire the event.

Comments

4

According to DOM Level 2 Event Specification:

The change event occurs when a control loses the input focus and its value has been modified since gaining focus.

That means that change event is designed to fire on change by user interaction. Programmatic changes doesn't cause this event to be fired.

Comments

0

As mentioned above change event is designed to fire by user interaction. If you want to do something after setting value programmatically you can use jQuery valHooks

var isChanged = false;
$.valHooks['text'] = {
    set: function (elem, value) {
        if ($(elem).is('.change')) {
            elem.value = value;
            isChanged = true;
            return true;
        }
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.