简体   繁体   中英

html onchange event not being called from ajax generated dropdown list

I have an ajax generated dropdown list. When the list generates it sends it back to the HTML like below. However, the HTML side onchange() event does not seem to kick in. How can I get this to work?

function listSess(){
 var name = document.getElementById("studentID").value;

 $.ajax({
    url : "<%=context%>/ListSessionsServlet?name=" + name,
    type : "POST",
    async : false,
    dataType: "json",
      success : function(data) {
          var toAppend = '';
          $.each(data,function(i,o){

              toAppend += '<option>'+o.sessid+'</option>';
             });

        $('#sessid')
            .find('option')
            .remove()
            .end()
            .append(toAppend);

      }  
});
} 


<select id="sessid" name="sessid" onchange="listStudents();">  <--onchange not working when getting ajax generated list
</select>

If you bind the change event using jQuery instead of inline as a tag attribute, you can trigger it with jQuery in your AJAX callback:

// Hook up the change event on DOM ready
$(function() {
    $('#sessid').change(function() {
        listStudents();
    });
});

function listSess(){
 var name = document.getElementById("studentID").value;

 $.ajax({
    url : "<%=context%>/ListSessionsServlet?name=" + name,
    type : "POST",
    async : false,
    dataType: "json",
      success : function(data) {
          var toAppend = '';
          $.each(data,function(i,o){
              toAppend += '<option>'+o.sessid+'</option>';
             });

        $('#sessid')
            .find('option')
            .remove()
            .end()
            .append(toAppend);

        $('#sessid').change(); // fire change
      }  
});
} 

<select id="sessid" name="sessid"></select>

Your current logic for building out the new <options> might not work without them having a value attribute. Here's how I might change it:

...
success : function(data) {
    var $sessid = $('#sessid');
    $sessid.find('option').remove();
    $.each(data, function (index, item) {
        $sessid.append($('<option />').val(item.sessid).text(item.sessid));
    });
    $sessid.val(data[0].sessid).change();
}  
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM