Add options to a DropDownList using Javascript and jQuery
February 23, 2011 Leave a comment
Adding items in Drop Down List or List Box using Javascript
<script type="text/javascript">
function AddItem(Text,Value)
{
// Create an Option object
var opt = document.createElement("option");
// Add an Option object to Drop Down/List Box
document.getElementById("DropDownList1").options.add(opt);
// Assign text and value to Option object opt.text = Text; opt.value = Value; }<script />
In JQuery like below,
var myOptions = { val1 : 'text1', val2 : 'text2' }; $.each(myOptions, function(val, text) { $('#mySelect').append( $('<option></option>').val(val).html(text) ); }); or,With no plug-ins, this can be easier without using as much jQuery, instead going slightly more old-school:var myOptions = { val1 : 'text1', val2 : 'text2' }; $.each(myOptions, function(val, text) { $('#mySelect').append( new Option(text,val) ); });If you want to use direct see below
$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")