Search code examples
jqueryasp.nethtml.dropdownlistfor

Fill DropDownList with options using comma-separated text


I have text like

important,offtopic,business

I want to use this string to fill a dropdown list. Data is comma-separated text, not JSON.

<select name="ctl00$Content$ucShare$ddlTag" id="ctl00_Content_ucShare_ddlTag">
<option value="important">important</option>
<option value="offtopic">offtopic</option>
<option value="business">business</option>
</select>

How can I do this with jQuery?


Solution

  • Get your text in array format.Then using each loop in jquery you can fill up dropdown list.

    var array = $('#yourfield').val().split(",");
    
    var dllist= $('#yourdropdownid');
    
    $.each(array,function(i){
        dllist.append(
            $('<option></option>').val(array[i]).html(array[i])
        );
    });
    

    working demo here Jsfiddle