Reputation: 6544
i am trying to create a select box dynamically with data that is within an array, I tried watching some JSON tutorials, yet having some trouble still.
var clothes = [
Red Dress:"reddress.png",
Blue Dress:"bluedress.png",
Black Hair Pin:"hairpin.png"
];
var select = '<select id="clothing_options">';
for(var i=0;i<clothes.length;i++)
{
select +='<option value="'+secondPart[i]+'">'+firstPart[i]+'</option>';
}
$('#select_box_wrapper').append(select+'</select>');
$('#clothing_options').change(function() {
var image_src = $(this).val();
$('#clothing_image').attr('src','http://www.imagehosting.com/'+image_src);
});
as you can see code is not fully functioning because it is not written correctly. How do I get the data for value from the second part and the option text from the first part? basically html should look like this
<select id="clothing_options">
<option value="reddress.png">Red Dress</option>
<option value="bluedress.png">Blue Dress</option>
<option value="hairpin.png">Black Hair Pin</option>
</select>
thanks for any explanations or suggestions. Just want this code to work, as I am just doing these codes for lessons for myself
Upvotes: 1
Views: 13578
Reputation: 362290
You could change your array to a JSON object..
var clothes = {
"Red Dress":"reddress.png",
"Blue Dress":"bluedress.png",
"Black Hair Pin":"hairpin.png"
};
and then iteration becomes easier..
for(var item in clothes)
{
$('<option value="'+item+'">'+clothes[item]+'</option>').appendTo('#clothing_options');
}
Here's the HTML:
<div id="select_box_wrapper">
<select id="clothing_options"></select>
</div>
Upvotes: 3
Reputation:
First problem:
var clothes = {
Red_Dress:"reddress.png",
Blue_Dress:"bluedress.png",
Black_Hair_Pin:"hairpin.png"
};
You can't have spaces in identifiers.
Second, to loop through an object:
for (var key in clothes)
{
select +='<option value="'+clothes[key]+'">'+key+'</option>';
}
Of course this has the undesired effect of showing 'Red_Dress' in the select box.
var clothes = {
"Red Dress":"reddress.png",
"Blue Dress":"bluedress.png",
"Black Hair Pin":"hairpin.png"
};
That will fix it.
Upvotes: 1