Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add option to select list in jQuery

My select list is called dropListBuilding. The following code does not seem to work:

 for (var i = 0; i < buildings.length; i++) {      var val = buildings[i];      var text = buildings[i];      alert("value of builing at: " + i.toString() + " is: " + val);      $("#dropListBuilding").addOption(val, text, false);  } 

This line dies:

$("#dropListBuilding").addOption(val, text, false); 

What is the right to add items to the drop down in jQuery? I have tested without that line and the buildings variable does have my data element.

like image 271
danila dinan Avatar asked Nov 13 '09 16:11

danila dinan


People also ask

How to add option in select in jQuery?

Method 1: Append the option tag to the select box The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection. Hence the option is added to the select element.

How to add item to dropdown in jQuery?

What we can do is, create a new select element and then append all options. Once loop is finished, append it to actual DOM object. var myOptions = { val1 : 'text1', val2 : 'text2' }; var _select = $('<select>'); $. each(myOptions, function(val, text) { _select.

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

Don't make your code so complicated. It can be done simply as below by using a foreach-like iterator:

$.each(buildings, function (index, value) {     $('#dropListBuilding').append($('<option/>', {          value: value,         text : value      })); });       
like image 182
HaMinh Nguyen Avatar answered Sep 21 '22 10:09

HaMinh Nguyen