21

Does anyone know how to set the options and the values of a dropdown menu using javascript or jquery? I'm using this HTML:

<select size="1" id="D1">
</select>

Thanks for the help.

1
  • What do you mean by 'set the options'? This is ambiguous.
    – Wes Crow
    Dec 28, 2011 at 21:09

5 Answers 5

52

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.

2
  • 1
    I think there is a typo at this line .html("text to be displayed"); remove semicolon at the end. It should be .html("text to be displayed").
    – Sivakumar
    Apr 27, 2015 at 13:50
  • @Sivakumar Wow, almost 4 years old and it went unnoticed...fixed. Thanks for bringing that up! hahaha
    – Purag
    Apr 28, 2015 at 2:30
14

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);
3

There are a few different ways. One is:

$("#D1").append("<option>Fred</option>");
3

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
1
$("#dropdown").html("<option value='val1'>label 1</option><option value='val2' selected='selected'>label 2</option>");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.