Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set select-options with JavaScript

How can I dynamically set the options from my html select field with Javascript? This is my page setup:

<form name="test">   <table>     <tr>       <td class='dataleft'>Product: </td>       <td><select name='inptProduct'></select></td>     </tr>   </table> </form> 

I have all values in an array. This is the location to set the <option>s.

for(var i = 0; i < productArray.length; i++) {     console.log("<option value='" + productArray[i] + "'>" + productArray[i] + "</option>"); } 

PS: jQuery can be used.


Solution: This is the final solution I was looking for. It does not apply the new options to the select field. It removes all first, and then adds the new ones:

var optionsAsString = ""; for(var i = 0; i < productArray.length; i++) {     optionsAsString += "<option value='" + productArray[i] + "'>" + productArray[i] + "</option>"; } $("select[name='inptProduct']").find('option').remove().end().append($(optionsAsString)); 
like image 810
nimrod Avatar asked Apr 20 '12 13:04

nimrod


People also ask

How do I create a dynamic selection in HTML?

var select = $("<select></select>"); var opt = $("<option></option"); opt. val("1"); opt. html("Option 1"); select.


2 Answers

wellyou have almost done it all:

var optionsAsString = ""; for(var i = 0; i < productArray.length; i++) {     optionsAsString += "<option value='" + productArray[i] + "'>" + productArray[i] + "</option>"; } $( 'select[name="inptProduct"]' ).append( optionsAsString ); 

EDIT removed $ wrapper around last optionsAsString as append automatically converts strings

like image 146
gotofritz Avatar answered Oct 01 '22 18:10

gotofritz


var $inputProduct = $("select[name='inputProduct']")  $(productArray).each(function(i, v){      $inputProduct.append($("<option>", { value: v, html: v })); }); 
like image 20
hunter Avatar answered Oct 01 '22 17:10

hunter