You are viewing limited content. For full access, please sign in.

Question

Question

Dynamically Populate Drop-down List

asked on October 6, 2016

I have an array which contains a list of value retrieved from a web service, I then need to iterate through this array and populate a drop-down list with the value within the array, but I am unable to get this working. I have written the below javascript to populate the drop-down list.

 

for(var i = 0; i<payee.length; i++) {
 $($('#q1 option')[i]).text(payee[i]);
}

 

I have an array call 'payee' which contains at least 2 value, but for some reason the above code only populates the first value into the drop-down list and ignores the rest. Does anyone have any idea? Thanks.

0 0

Answer

SELECTED ANSWER
replied on October 6, 2016

Based on your code above, you are simply taking the first option in the drop down and changing its text property to the value in the array which will always be the value of the last item in the array. You need to rather replace the options in the drop down with your options generated from your array. The following code should do just that:

var s;
for(var i = 0; i<payee.length; i++) {
   s += '<option value="' + payee[i] + '">' +payee[i] + '</option>';
}
$('#q1 select').html(s);

Note: The "value" in the option is optional

1 0
replied on October 6, 2016

Works like a charm. Thanks!

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.