1

I have several elements on my page, and some of them are wrapped in a div with a class that I care about (in this case, "workItemRow"). I only want elements that have an ancestor with class workItemRow to trigger an event. The problem is, every element is bound to the event, not just the ones with the ancestors.

Ex. (Shortened version of the actual code)

<div class="workItemRow">
<select class="objective"></select>
</div>

<div>
<select class="objective"></select>
</div>

and then my jQuery:

$('body').on('change', '.workItemRow .objective', function () {
   alert("Why isn't this working?");
});

Every time I change the select that is in the second div (the one without any classes), that event is still being triggered, and I don't understand why. I have tried changing the selector to ".workItemRow > .objective" but it still always calls it.

5
  • 2
    It works fine jsfiddle.net/8sREv Commented Apr 10, 2012 at 21:08
  • does this code execute in the head before the body has loaded? Try $(document).on... instead. Commented Apr 10, 2012 at 21:08
  • It's wrapped in $(document).ready... Commented Apr 10, 2012 at 21:12
  • 3
    There's nothing wrong with your JS so there's something else going on. Is there a .workItemRow class at a higher level that is allowing the match even when you don't want it? Commented Apr 10, 2012 at 21:13
  • I figured it out. I should have mentioned that every time a div is changed, a new div is created that doesn't have the "workItemRow" class. Also, the div that was just changed gets the class "workItemRow" added to it. I didn't think that adding the class as the result of a change would happen before the event is done resolving, but apparently it does. Commented Apr 10, 2012 at 21:45

1 Answer 1

1

you can do:

$('body').on('change', '.workItemRow > .objective', function () {
   alert("Why isn't this working?");
});

that will select elements(.objective) wich are wrapped in a element.workItemRow

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.