3

I have a select box:

<select id="translationOptions" name="translationOptions"></select>

And I have a js array

var translationOptions = ["Egyptian Hieroglyphs", "Al Bhed (Final Fantasy X)", "Futurama"];

How would I auto populate the select box based on the var translationOptions?

Mat
  • 202,337
  • 40
  • 393
  • 406
RSM
  • 14,540
  • 34
  • 97
  • 144

3 Answers3

4
$.each(translationOptions, function(key, value) {   
    $('#mySelect')
         .append($("<option></option>")
         .attr("value",key)
         .text(value)); 
});

What is the best way to add options to a select from an array with jQuery?

Community
  • 1
  • 1
Steve
  • 2,936
  • 5
  • 27
  • 38
  • How could you pull the data from a couple of `INPUT` fields into the array to then feed into the above? I tried `var translationOptions = ['$("input[name="inputboxname"]").val()'];` but it just returns `['$("input[name="inputboxname"]").val()']` as the SELECT option – Jez Aug 21 '14 at 14:18
3
$.each(translationOptions, function(index, value) {
    $('#translationOptions').append($("<option />").val(index).text(value));
});

This uses text for display and index in the array for value.

CD Smith
  • 6,597
  • 7
  • 40
  • 66
Porco
  • 4,163
  • 3
  • 22
  • 25
2

You can create options dynamically and append to select box in this way as well.

jQuery.each(translationOptions, function(key, value) {
    jQuery('<option/>', {
       'value': key,
       'text' : value
}).appendTo('#translationOptions');
Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101