1

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

2 Answers 2

3

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>

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the explanation. Now for the line of for(var item in clothes) can item be anything?
yes, the var 'item' could be called anything. It represents each item in the json object.
1

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.

1 Comment

Thank you for the explanation of all of this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.