Jquery – Fill a select/menu object using jQuery

fillitemsjquerymenuselect

I need to fill a object using jQuery
I have a dialog (jQueryUI) that shows. Once dialog closes, the object should be filled with items taken from a mySQL table

I have a function fill_select() located in my JS code… and I should place code there, because I call this JS function frequently.

PS: I should remove all the items before filling select again

Best Solution

http://docs.jquery.com/Ajax

The reason I used JSON in this example is because you typically want AJAX calls to be light weight. Building an HTML string on the client side is relatively fast for most browsers (You probably know which one is not that fast...). In any case you don't want to append elements to the select one at a time for speed considerations.

If you don't know what JSON is take a look at this.

http://json.org/

    function fillSelectList(param1, param2) {
        $.ajax({
            type: "GET",
            url: "myUrl.php",
            data: { Param1: param1, Param2: param2 },
            dataType: "json",
            async: true,
            success: function(data, textStatus) {
                var html = "";
                for (var i = 0; i < data.length; i++) {
                    html += "<option value=\"";
                    html += data[i].value + "\">";
                    html += data[i].text + "</option>";
                }

                $("#mySelectList").empty().append(html);
            }    
        });        
    }