Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set options of a dropdown using Javascript/jQuery?

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.

like image 773
Joey Morani Avatar asked Dec 28 '11 21:12

Joey Morani


People also ask

How can I set the value of a Dropdownlist using jQuery?

To achieve this feat you can use various methods, two of those methods will be explained below. Used Function: val() function: It sets or returns the value attribute of the selected elements. attr() function: It sets or returns the attributes and values of the selected elements.

How do I select a specific Dropdownlist using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).

How show selected value from database in dropdown using jQuery?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

How can set the selected value of dropdown in jQuery using ID?

Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id.


3 Answers

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.

like image 87
Purag Avatar answered Sep 21 '22 19:09

Purag


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);
like image 41
Andrew Whitaker Avatar answered Sep 21 '22 19:09

Andrew Whitaker


There are a few different ways. One is:

$("#D1").append("<option>Fred</option>");
like image 21
scrappedcola Avatar answered Sep 22 '22 19:09

scrappedcola