Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery create select list options from JSON, not happening as advertised?

How come this doesn't work (operating on an empty select list <select id="requestTypes"></select>

$(function() {

        $.getJSON("/RequestX/GetRequestTypes/", showRequestTypes);

    }
    );


    function showRequestTypes(data, textStatus) {

        $.each(data,
            function() {

                var option = new Option(this.RequestTypeName, this.RequestTypeID);
                // Use Jquery to get select list element
                var dropdownList = $("#requestTypes");

                if ($.browser.msie) {
                    dropdownList.add(option);
                }

                else {

                    dropdownList.add(option, null);

                }
            }
            );

        }

But this does:

  • Replace:

    var dropdownList = $("#requestTypes");

  • With plain old javascript:

    var dropdownList = document.getElementById("requestTypes");

like image 811
Codewerks Avatar asked Sep 18 '08 17:09

Codewerks


3 Answers

$("#requestTypes") returns a jQuery object that contains all the selected elements. You are attempting to call the add() method of an individual element, but instead you are calling the add() method of the jQuery object, which does something very different.

In order to access the DOM element itself, you need to treat the jQuery object as an array and get the first item out of it, by using $("#requestTypes")[0].

like image 187
Jim Avatar answered Oct 24 '22 09:10

Jim


By default, jQuery selectors return the jQuery object. Add this to get the DOM element returned:

 var dropdownList = $("#requestTypes")[0];
like image 21
John Sheehan Avatar answered Oct 24 '22 11:10

John Sheehan


For stuff like this, I use texotela's select box plugin with its simple ajaxAddOption function.

like image 4
Shinhan Avatar answered Oct 24 '22 09:10

Shinhan