Reputation: 1615
I have a simple list that I put into an array. What I'd like to do is once a specific item in that list/array has been chosen: show content-X.
How do I structure the If statement to check for a specific selection within the array to then force a particular action?
<select name="list" id="list">
<option name="one" id="one">One</option>
<option name="two" id="two">two</option>
<option name="three" id="three">three</option>
</select>
var ListArr = [];
var list = document.getElementById("list");
for(i=0; i<list.options.length; i++)
{
ListArr[i]=list.options[i].value;
}
Upvotes: 0
Views: 951
Reputation: 1299
Try this:
HTML:
<select name="list" id="list">
<option name="one" id="one">One</option>
<option name="two" id="two">two</option>
<option name="three" id="three">three</option>
</select>
JS
(function(){
var ListArr = [];
var list = document.getElementById("list");
for(i=0; i<list.options.length; i++)
{
ListArr[i]=list.options[i].value;
}
list.addEventListener("change", function(){
var x = document.getElementById("list").selectedIndex;
console.log("specific item in that list/array has been chosen: show content- "+ListArr[x]);
alert("specific item in that list/array has been chosen: show content- "+ListArr[x]);
});
}());
Upvotes: 1
Reputation: 10180
If you change the way your Select menu is setup, you can easily show an element based on the value of the option like so:
HTML
<select name="list" id="list">
<option name="one" value="one">One</option>
<option name="two" value="two">two</option>
<option name="three" value="three">three</option>
</select>
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
Javascript
document.getElementById("list").onchange=function(){
var hiddenID = this.value;
document.getElementById(hiddenID).style.display = "block";
};
You basically need to give an ID
to an element that matches the value
of the option in the select list.
Here is a fiddle: https://jsfiddle.net/q30gcfg4/
Upvotes: 0
Reputation: 694
You could use something like this (just replace the alert with your own functionality):
function changeOption() {
var selected = document.getElementById("list").value;
alert(selected);
}
<select name="list" id="list" onchange="changeOption()">
<option name="one" id="one">One</option>
<option name="two" id="two">two</option>
<option name="three" id="three">three</option>
</select>
Upvotes: 0