Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery can't bind event to AJAX loaded element using .on() [duplicate]

Using .load, I'm loading the following content into #step_2 div:

<div id="step_2">
    Select a subcategory:
    <select id="subcategory_id" name="subcategory_id">
        <option value="0">All subcategories</option>
        <option value="68">Cool</option>
        <option value="15">Cooler</option>
        <option value="74">Excellent</option>
    </select>
</div>

I'm then trying to detect when user selects something:

$("#subcategory_id").on("change", function(){
    alert( 'Success!' );
});

but with no success. Does anyone see what I'm doing wrong? Help greatly appreciated.

NOTES:

Here's the full CSS path as seen by FireBug:

html.js body div#container div#main form div#step_2 select#subcategory_id

Here's the full Javascript file, if context matters:

$(document).ready(function() {

    $("#category_id").change(function() {
        $("#spinner").show();
        $("#step_2").load("process.php?selected=category", { value: $(this).val() }, function() {
            // Do something to say the data has loaded sucessfully
            $("#spinner").hide();
        });
    });
            
    $("#subcategory_id").on("change", function(){
        alert( 'Success!' );
    });
    
});
like image 437
CodeVirtuoso Avatar asked Dec 01 '11 15:12

CodeVirtuoso


2 Answers

In this case you need to use on in a similar way to delegate, the syntax you are using is the replacement for bind.

$("#step_2").on("change", "#subcategory_id", function(){
    alert( 'Success!' );
});

The first selector has to be an element that won't be replaced. This way, when the event bubbles up to this point it is caught. You then specify the actual element that will trigger the event as the 2nd parameter of .on.

like image 155
Richard Dalton Avatar answered Nov 04 '22 06:11

Richard Dalton


on(...) won't subscribe to events that aren't on the page yet without the proper setup. To do what you want, you should try the following:

$(document).on("change", "#subcategory_id", function(){
    alert( 'Success!' );
});

To make this more efficient, you should replace $(document) with the closest parent of the element that you know will be on the page when this code is called.

like image 13
Dan Herbert Avatar answered Nov 04 '22 04:11

Dan Herbert