0

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;
}
1

3 Answers 3

1

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]);
});
}());

Working jsfiddle link

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

Comments

0

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>

Comments

0

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/

Comments

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.