Search code examples
jqueryhtml-selectvelocityjquery-events

Change event on a dynamically loaded option list is not called


I would like to load dynamically (using a velocity object) a select drop down list, and then associate the change event with it; to do it I wrote so:

$(function() {
        var tableList = $("#tableList");
#foreach( $i in $it.getTableNames() )
        tableList.append($("<option></option>")
            .text("$!esc.html($i)"));
#end
        tableList.change(function(){
            jQuery.ajax({
            type: "GET",
            url: "$it.uri" + "/tablesColumnNames",
            dataType: "json",
            success: loadTableResponse
            });
        });
}

But despite the option list is correctly loaded the change event can never be triggered. What is wrong with this?


Solution

  • Do

    $(function() {
      $(document.body).on("change","#tablelits",function() {
                  //...
             });
      //append your select/options whenever you want
    })
    

    NB:cache your $(document.body) obviously, the previous code is just illustration of the mechanic

    NB: don't append your options one by one create a var with all your options within your select box & then append the select at once using appendTo (because append tends to go wrong with ie)