How to set options of a dropdown using Javascript/jQuery?
You don't even necessarily need jQuery:
var select = document.getElementById("D1"),
opt = document.createElement("option");
opt.value = "value";
opt.textContent = "text to be displayed";
select.appendChild(opt);
Example.
But here it is with jQuery anyway:
$("select#D1").append( $("<option>")
.val("value")
.html("text to be displayed")
);
Example.
There are a few different ways. One is:
$("#D1").append("<option>Fred</option>");
Here's yet another way to remove options using javascript (similar to Andrew Whitaker's answer) by using the options array:
var select = document.getElementById("D1");
select.options.length = 0;//remove all options
Yet another way of doing it, using select
's add method:
var select = $("#select")[0];
select.add(new Option("one", 1));
select.add(new Option("two", 2));
select.add(new Option("three", 3));
Example: http://jsfiddle.net/pc9Dz/
Or another way, by directly assigning values to the select
's options
collection:
var select = $("#select")[0];
select.options[0] = new Option("one", 1);
select.options[1] = new Option("two", 2);