开发者

Automatically updating dropdown after change event

开发者 https://www.devze.com 2023-03-19 15:50 出处:网络
I have a dropdown list which is populated via a jquery ajax call when another dropdown list is changed, on the change() event, the code which does this:

I have a dropdown list which is populated via a jquery ajax call when another dropdown list is changed, on the change() event, the code which does this:

    //dropdowns switching        
        $("#eventActivity").bind("change", (function()
        {                     
            $.ajax({
                type:"POST",
                url:"<?php echo site_url('events/get_locations_for_activity'); ?>" + "/" + $(this).val(),
                data: "activityID=" + $(this).val(),
                cache: false,
                dataType: "json",
                success:function(data)
                {
                    //empty the ddl
                    $(".locationDDL").children("select:first").children("option").remove();
                    //go through the json data returned and edit the drop down
                    for( var i = 0 ; i < data.length ; i++)
                    {
                        $(".locationDDL").children("select:first").append("<op开发者_如何学Gotion value=\"" + data[i].locationID + "\">" + data[i].name + "</option>");
                    }

                }
            });
        })).change(); //force change to run once so it works on load for the first dropdown option

Now these dropdowns are on a dialog which pops up when the "edit" button is clicked. I'm passing the data through to the edit dialog so I can pre-fill the fields on the dialog. It all works fine except for setting the dropdowns to the correct values.

The code I use to do this is here:

$("#eventActivity").val(event.activityID);
$("#eventActivity").change(); //force the change handler to update the dropdowns
$("#eventLocation").val(event.locationID); 

As you can see, I set the value of the first dropdown, trigger the change event which should load new values to the second dropdown, then set the value of the second dropdown. The problem is that the third line of code (setting #eventLocation) doesn't work, instead the dropdown is left with it's default value selected, the first value in the drowdown list.

Any suggestions are much appreciated!


You should set the value of the last dropdown in the success callback of your ajax request. If the last value setting depends on the ajax request being complete, you should have it in the callback. It is likely your request hasn't been completed by the time that last value setting happens.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号