javascriptjqueryasp.netjquery-uidrop-down-menu

Append values to asp.net dropdownlist with jQuery


I am trying to append a value with jQuery but with the ways I am trying the option doesn't want to append. This is what I am trying (for test purposes):

 $('#<%=btnSelectAgentAdd.ClientID %>').click(function () {              
                var myOptions = {
                    val1: 100,
                    val2: 'text2'
                };
                $('#<%=ddlAgentName.ClientID %>').append(new Option(myOptions.val2, myOptions.val1));             
             });

I also tried this:

 $('#<%=btnSelectAgentAdd.ClientID %>').click(function () {
                var mySelect = $('#<%=ddlAgentName.ClientID %>');
                var myOptions = {
                    val1: 100,
                    val2: 'text2'
                };
                $.each(myOptions, function(val, text) {
    $('#<%=ddlAgentName.ClientID %>').append( new Option(text,val) );
});           
             });

And this:

 $('#<%=btnSelectAgentAdd.ClientID %>').click(function () {
                var mySelect = $('#<%=ddlAgentName.ClientID %>');
                var myOptions = {
                    val1: 100,
                    val2: 'text2'
                };
                $.each(myOptions, function(val, text) {
    mySelect.append(
        $('<option></option>').val(val).html(text)
    );
             });

None of them are working. Debugging with Firebug shows that the error is happening on the last step when the values are to be appended to the dropdownlist.


Solution

  • Try like this:

    $.each(myOptions, function (val, text) {
        mySelect.append($('<option />', {
            value: val,
            text: text
        }));
    });
    

    FIDDLE DEMO