简体   繁体   中英

How to Add options to select box based from an array?

I am stuck with this issue. What I want to do is to create the option values in a select box on the fly with the use of jquery javascript.

For example, if I have a question like what are your favourite fruits? So users should be able to select an answer from the default select box eg "Apple, Orange, Pear, Banana". Then they can click on a click "Add more fruits" and a second select box will appear with the same array of selection.

Basically with reference to the previous stack overflow question from another member , I could only piece up the information till here. But I could not have the option values printed out from the array, aside from the default "Select Fruit" option, at runtime.

$(function() {
// set the array
var fruit = new Array("Apple", "Orange", "Pear", "Banana");

function addFruit() {
    $.each(fruit, function(key, value) {   
        $('#fruit')
        .append($('<option>', { value : key })
        .text(value)); 
    });
}

var i = $("li").size() + 1;
$("a#addmore").click(function() {
    $("#addmore_row").append('<li>' +
    '<select name="fruit[]" id="fruit">' +
    '<option value="">Select Fruit:</option>' +
    addFruit()                
    + '</select>' +
    '</li>');
    return false;
});

});

Can anyone please help me out with this? Thank you very much.

addFruit is being called while it's constructing the string representing the select . Since it's still constructing the string to append, the select doesn't actually exist yet, but addFruit is still being called. In short, move addFruit out of the string concatenation to after you've appended the select .

In other words, this:

$("#addmore_row").append('<li>' +
'<select name="fruit[]" id="fruit">' +
'<option value="">Select Fruit:</option>' +
'</select>' +
'</li>');
addFruit();
return false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM