Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onchange wont fire after programmatically changing html select dropdown

I have a select inside HTML

<select id="league" name="league">

which I'm listening for changes inside my javascript.

var league = dojo.byId("league");
dojo.connect(league, "onchange", function (evt) { //do stuff }

Which works fine. However I have a link that I can click which updates the select:

<a href=javascript:void(0) onclick="updateSelection(league);"> League </a>

The link works as it updates the selected value of the select with the following function.

function updateSelection(NewLeague){
dojo.byId('league').value = NewLeague;  // works
dojo.byId('league').onChange;   //this isnt working
//dojo.byId('league').onChange();  //this throws: TypeError: dojo.byId("league").onChange is not a function 
}

My problem, as I've read through other stack posts is that programmatically updating the value wont trigger onChange, thus I need to call onchange in the code (shown above). As per the comments inline, the onChange isn't being triggered or throws an error. My first thought that it has something to do with the dojo.Connect which listens for onChange, but I havent found any information that says I cant do this, nor any explanation how to get around it.

Any ideas?

like image 264
KHibma Avatar asked Oct 18 '12 16:10

KHibma


People also ask

Why is Onchange not working?

onchange is not fired when the value of an input is changed. It is only changed when the input's value is changed and then the input is blurred. What you'll need to do is capture the keypress event when fired in the given input. Then you'll test the value of the input against the value before it was keypressed.

Can I use Onchange in select tag?

The other difference is that the onchange event also works on <select> elements.

What triggers Onchange event?

The onchange JavaScript event is triggered when an element is changed and then loses focus. In the context of a textarea , this happens when the content of the textarea is modified and then the textarea loses focus because the user clicks away or presses the tab key.


2 Answers

Select onchange doesn't fire for programattic changes, you need to fire it yourself with league.onchange();

As noted by @Greg, the call should be lowercase.

Additionally, I don't know if dojo has a trigger method, but in jQuery this would be done as jQuery('#league').trigger('change').

Depending on your version of dojo you may also want to check: http://dojotoolkit.org/reference-guide/1.8/dojo/connect.html

like image 152
Bob Davies Avatar answered Oct 01 '22 01:10

Bob Davies


Have you tried just calling the select by it's id using normal js?

document.getElementById('league').onchange.call();
like image 25
Rick Calder Avatar answered Oct 01 '22 03:10

Rick Calder