0

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 e.g. "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.

Community
  • 1
  • 1
jl.
  • 2,209
  • 12
  • 49
  • 61

1 Answers1

1

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;
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • i tried, but i seems to append to the default select box which was within the html, instead of adding to the newly created select box. Do I have to use different name for the new select box, instead of following the same name for the first select default box? – jl. Jul 14 '11 at 02:42
  • wait i think there is an issue, for the second select box it works, but for the third and fourth it doesn't append the values to the select box. May I know what can be done? – jl. Jul 14 '11 at 02:48
  • If the link is being clicked multiple times, you'll need to use a unique ID for each `select` you add. – icktoofay Jul 14 '11 at 02:49