1

I would like to be able to detect when the selected value of dropdown has changed using jQuery. The selected value of the dropdown is changed by other JavaScript, so I want to be able to catch this event.

I can see the dropdown changing, however the following code does not capture the event correctly. Does the change event only capture the event when it is performed by the user and not other code?

$('select[name=b_country]').live('change', function() {
    alert('the country dropdown has changed');
});

<select name="b_country" style="display: block;">
crmpicco
  • 16,605
  • 26
  • 134
  • 210

1 Answers1

2

Yes, only user interactions fire the event. Otherwise you wouldn't be able to (re)set values in a listener without entering an infinite loop.

If you want to inform other (listening) scripts that you changed the value, you can manually trigger an event. With jQuery, this is easy:

$('select[name=b_country]').val(…).change();
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • The problem I have here is that the code that changes the `b_country` dropdown is not mine. It is third party JavaScript and I don't have any control over it. Is there no other way to capture when it is changed? – crmpicco Sep 18 '12 at 16:05
  • No. If that third party script doesn't offer a proper API (to hook on events like this, etc), I'd recommend to use another one. – Bergi Sep 18 '12 at 16:09
  • That's frustrating. I would have thought you could have listened on a specific element in the DOM and when it changed state, by any means, you could capture the change. – crmpicco Sep 18 '12 at 16:31
  • The API I am using doesn't document the callbacks, however their support channel has advised that they do exist. This allowed me to implement the feature I needed. – crmpicco Sep 20 '12 at 09:58
  • Uh, using undocumented features is like a hack ;-) – Bergi Sep 20 '12 at 10:39
  • I'm not sure how much I agree with the statement that "using undocumented features is like a hack". I am using valid API code and JavaScript, so it's not really a hack. My hands are tied with regards to the fact that the callbacks are undocumented, so there's nothing I can really do about that. I am frustrated that the technology provider doesn't provide documentation to the callbacks, but they did provide suitable support and the callbacks themselves work. – crmpicco Sep 20 '12 at 15:09