0

I am doing an Dom change and my elements gets formed like below

   <select class="foodselect" data-table="table1"  style="width: 100px;">
                <option value="100">
                  Per 100g
                </option>
                <option value="225">
                  1 cup, mashed 
                </option>
                <option value="150">
                  1 cup, sliced 
                </option>
    </select>

    <select class="foodselect" data-table="table2"  style="width: 100px;">
                <option value="100">
                  Per 100g
                </option>
                <option value="225">
                  1 cup
                </option>
                <option value="150">
                  1 oz
                </option>
    </select>

so when I usually change options below code used to work

$('.foodselect').on("change","select", function(event){

    alert("hi");
    });

But when I do Dom change its not working.

Vishnu
  • 2,372
  • 6
  • 36
  • 58

1 Answers1

0

The problem you're having is that you're binding the event handler to the specific element that is, according to what you wrote above, is being added and removed from the DOM dynamically based on the return of an AJAX call.

As implied by the other answer that was here originally, you want to instead bind the event handler to the parent of this select element instead. Assuming that the parent is never removed (and if it does, go a level higher), as Benjamin Gruenbaum said, the second parameter of the on method accepts a context-sensitive selector which specifies on which elements to trigger the event, like so:

$(".your_parent_element").on("change", "select.foodselect", function(event) {
    alert("hi");
});

Side note: The reason the other answer didn't work is probably because they got the descendent filter incorrect. Also, you can technically bind on "body" but you shouldn't need to do that (unless your parent really is "body", which would be odd)

Paul Richter
  • 10,908
  • 10
  • 52
  • 85