Victor Lundgren Victor Lundgren - 4 months ago 8
Javascript Question

JQuery on change event firing for the wrong element

I have two

<select>
elements:
select.exerciseType
and
#moduleTopic
, each with their own handler wrapped around the
document
. I believe it's important to know that
select.exerciseType
is dinamic and there can be multiple of those.
Their events are:

$(document).ready(function() {
$(document).on("change", $("select.exerciseType"), function(e) {
<!--Code not really important-->
}
$(document).on("change", $("#moduleTopic"), function(e) {
<!--Code not really important-->
}
}


My problem is, when I change the selected option in one of those selects, both those events are firing. Why is the selector in the on() function not working and how can I make it work?

Answer

Syntax for jQuery .on handler is .on( events [, selector ] [, data ], handler ) where second argument is string

In your case, as it is not string, it is omitted and the event is always triggered when it reaches the selected element!

$(document).ready(function() {
  $(document).on("change", "select.exerciseType", function(e) {});
  $(document).on("change", "#moduleTopic", function(e) {});
});