简体   繁体   中英

JQuery.append() after ajax success is not triggered

My mind is blowing up looking for the reason and the solution of my problem. I know I miss something but I have no idea where it is. My objective is having an ajax call after the drop down is changed, then append option in select multiple.

Here is what I have:

$(document).ready( function(){
    $('#myselect').append("<option value='test1' selected>Test1</option>"); //this works

    $("#mydropdown").on('change', function(){
        $.ajax({
            type: "POST",
            url: "somepage.php",
            data: $("#someForm").serialize(),
            success: function(msg)
            {   
                alert("Hello World"); //this is triggered
                //below line of code does not work
                $('#myselect').append("<option value='test3' selected>Tes3</option>");
            }
        });
    });
});

Why is this happening?

So I have got a work around to my problem. I put a div with a specific ID called theDiv around the select and initialize it as usual. Then in my AJAX request I put

$( "#theDiv" ).empty(); //empty the diev so that select will be removed
//append select
$("#theDiv").append('<select multiple="multiple" id="myselect" name="myselect[]"><option>Some option</option></select>');
InitalizeMultiSelect(); //re-initialize the multiSelect

Right now it is working OK for me. Might not be efficient but seems I did not found any way to de-initialize the multiSelect, so I guess this is the best solution for me.

Thank you for all your time and helps.

the code

$('#myselect').append("<option value='test3' selected>Tes3</option>");

seems ok to me. But for instance check the two suggestion I am giving you

1) First try this

change "<option value='test3' selected>Tes3</option>";

to '<option value="test3" selected>Tes3</option>'

2) Also try to use selected='selected'

may be that can also cause problem

I misunderstood that myselect and mydropdown are same dropdowns..

Sorry, anyways your code is allright.

do one thing, try to remove the class of the #myselect(if any class is there) to see if your code works

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