I have 3 <select> menus, each with change events working on them. Break down of the code looks like this:
$(document).ready(function(){
// some code
$("#selectOne").change(function() {
// some code inc ajax request
$("#selectTwo").change(function() {
// some code inc a different ajax request
});
$("#selectThree").change(function() {
// some code inc a yet another ajax request
});
});
});
The problem with the above is that, while selectOne works fine, and selectTwo seems to work fine also, if I change selectThree, the code for both selectTwo AND selectThree fires at the same time. Depending on the sequence of selection of any of the 3 selects, the response of selectThree.change can be to display and hide each of the previous responses, before settling on displaying an incorrect response.
What I’d like to do is this:
$(document).ready(function(){
// some code
$("#selectOne").change(function() {
// some code inc ajax request
});
$("#selectTwo").change(function() {
// some code inc a different ajax request
});
$("#selectThree").change(function() {
// some code inc a yet another ajax request
});
});
In this scenario, selectOne works fine, but selectTwo and selectThree don’t respond to change.
Is there a way of correcting any of this, so that as each element is changed, only the correct change event is fired?
It seems that when your document is loaded there is no select elements with id “selectTwo” or “selectThree”. Similarly in the first case, there is no “selectThree” when the eventhandler of “selectOne” executes. That’s why the corresponding event handlers does not execute. There is two way you can handle this proplem.
1 – Assing handlers when the elements are created.
2 – Use
.on()instead of.change():