Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding options to a <select> using jQuery?

What's the easiest way to add an option to a dropdown using jQuery?

Will this work?

$("#mySelect").append('<option value=1>My option</option>'); 
like image 767
Ali Avatar asked Apr 11 '09 14:04

Ali


People also ask

How do I add dynamic options to select?

To dynamically add options to an existing select in JavaScript, we can use a new Option object append it to the select element with the options. add method. to add a select element. to select the select element with document.

Can we add class in select option in jQuery?

jQuery addClass() MethodThe addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute.

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”).


1 Answers

Personally, I prefer this syntax for appending options:

$('#mySelect').append($('<option>', {     value: 1,     text: 'My option' })); 

If you're adding options from a collection of items, you can do the following:

$.each(items, function (i, item) {     $('#mySelect').append($('<option>', {          value: item.value,         text : item.text      })); }); 
like image 61
dule Avatar answered Oct 09 '22 03:10

dule