I have developed a script that generates a drop-down menu and updates the .box div with a new color and image.
Below is the HTML & Java code:
<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;
}
The functionality is working perfectly as intended.
However, I am looking to expand this functionality to around 100 fields which can be quite exhausting and inefficient to do manually (although CSS may still need manual adjustments).
My goal is to enhance the dynamic nature of my script by allowing me to add colors once in an options array, and then have the HTML and JavaScript loop through them for display actions.
Therefore, my initial question is how can I convert my HTML chunk into a loop to iterate over my options array?
Secondly, how can I streamline my code using the options array?
Thank you!