Reputation:
I'm trying, without success, to fill an html select by using javascirpt (jquery).
I know how to fill a select with jquery (by using the method 'append').
What I can't do is that I have to read the value for the select, from a string that is in the following format: "AA,B,CCC,DD,E"; So the various values are separeted by a comma.
The result have to be the following:
<select id="select">
<option value="AA">AA</option>
<option value="B">B</option>
<option value="CCC">CCC</option>
<option value="DD">DD</option>
<option value="E">E</option>
</select>
Can someone help me ??
Thanks :)
How can I insert as 'value' for the select the values obtained from another string in the same format (str2= "1,2,3,4,5") ?
<select id="select">
<option value="1">AA</option>
<option value="2">B</option>
<option value="3">CCC</option>
<option value="4">DD</option>
<option value="5">E</option>
</select>
Sorry for this questions, but I'm really new in js and jquery.
Thanks ;)
Upvotes: 0
Views: 4556
Reputation:
I have resolved it this way:
var str = "AA,B,CCC,DD,E";
var str2 = "1,2,8,4,5";
str = str.split(',');
str2 = str2.split(',');
$.each(str, function (idx, val) {
$('#select1').append("<option value='" + str2[idx] + "'> " + val + " </option>");
});
Upvotes: 0
Reputation: 80647
A simple use of .split()
will help.
var str = "AA,B,CCC,DD,E";
str = str.split(',');
$.each(str, function (idx, val) {
console.log(val);
$('#select').append("<option value='" + val + "'> " + val + " </option>");
});
And the fiddle.
Upvotes: 5