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?

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.