RSM
RSM

Reputation: 15108

Auto populate select box using Javascript and jQuery

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?

Upvotes: 3

Views: 6612

Answers (3)

Nishu Tayal
Nishu Tayal

Reputation: 20830

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');

Upvotes: 2

Porco
Porco

Reputation: 4203

$.each(translationOptions, function(index, value) {
    $('#translationOptions').append($("<option />").val(index).text(value));
});

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

Upvotes: 3

Steve
Steve

Reputation: 3046

$.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?

Upvotes: 4

Related Questions