So I have this script that outputs a drop down menu and refreshes the .box div with a new color and image.
HTML & Java:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div>
<select id="color">
<option style="display: none;">Choose Color</option>
</select>
</div>
<div class="red box">You have selected <strong>red option</strong> so i am here
<img src="http://i46.tinypic.com/2epim8j.jpg" />
</div>
<div class="green box">You have selected <strong>green option</strong> so i am here
<img src="http://i49.tinypic.com/28vepvr.jpg" />
</div>
<div class="blue box">You have selected <strong>blue option</strong> so i am here
<img src="http://i50.tinypic.com/f0ud01.jpg" />
</div>
<script>
$(document).ready(function() {
$("select").change(function() {
$("select option:selected").each(function() {
if ($(this).attr("value") == "Red") {
$(".box").hide();
$(".red").show();
}
if ($(this).attr("value") == "Green") {
$(".box").hide();
$(".green").show();
}
if ($(this).attr("value") == "Blue") {
$(".box").hide();
$(".blue").show();
}
});
}).change();
});
var select = document.getElementById("color");
var options = ["Red", "Blue", "Green"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
</script>
CSS:
.box {
padding: 20px;
display: none;
margin-top: 20px;
border: 1px solid #000;
}
.box img {
float: right;
width: 150px;
height: 100px;
}
.red {
background: #ff0000;
}
.green {
background: #00ff00;
}
.blue {
background: #0000ff;
}
It all works beautifully.
Thing is, I want to scale this up into roughly 100 fields and doing so manually is both exhausting and inefficient (though the CSS will probably be manual).
So what I want to do is make my script more dynamic, by allowing me to create a color once (in my established options array) and then the html and javascript would loop through it to display their actions.
So then I guess my first question is how can I take my html chunk and turn it into a loop that goes through my options array?
Secondly, how can I take my options array to get my code simplified?
Thank you