Joey Morani Joey Morani - 19 days ago 6
Javascript Question

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.

Answer

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.

Comments