简体   繁体   中英

Dropdown event not called after ajax Response in Javascript

Here is my code:

 $.ajax({ url: "server.do?button=go&flag=false", type: "GET", success: function(data) { var respContent = ""; respContent += data; $("#ajaxResponse").show(); $("#ajaxResponse").html(data); } }); 
 <span id="ajaxResponse" style="display:none"></span> 

This is then the HTML I have which is binded to ajaxResponse span:

 <span style="" id="ajaxResponse"><select tabindex="12" id="aId" name="aId"><option value="ANY">ANY</option><option value="1">ABC</option><option value="2">XYZ</option></select></span> 

As you can see above, from the server I am sending back the HTML response for a dropdown. The dropdown is well formed and is appended to the ajaxResponse div. The dropdown appears and is well formed in the developer tools browser control. However the dropdown does not fire the jQuery on change event. I think the DOM has already loaded and jQuery is unable to find the ID for the On change event to fire.Which means:

  $("#aId").change(function(e) { //How do i fire this event ?? alert('I am never called'); }); 

My question is how to call the above function for the dropdown sent from server side ?

Try this :

$.ajax({
    url: "server.do?button=go&flag=false",
    type: "GET",
}).done(function (data) {
    var respContent = "";
    respContent += data;
    $("#ajaxResponse").show();
    $("#ajaxResponse").html(data);
})
.fail(function () {
    console.log("error");
});

Try this:

jQuery 1.7 onwards use "on", for prior version you can use "live"

$(document).on('change','#aId', function(e) { //How do i fire this event ?? alert('I am never called'); });

The element (#aId) does not available when the document ready.So the change event will not assigned, for that we need to bind the change event dynamically.

You must bind the event handler everytime you render it after the ajax response, in this way (following your example):

$.ajax({
    url: "server.do?button=go&flag=false",
    type: "GET",
    success: function(data) {
        var respContent = "";
        respContent += data;
                    $("#ajaxResponse").show();
        $("#ajaxResponse").html(data);
        // add a event handled for 'change' every time you render it
        $("#aId").change(function(e) {
           var select = $(this);
           console.log('this should work.',select.val());
        });
    }
    });

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