Issue
I started learning DOM, i just wanted to test something, I’ve created drop down list using i wanted to display data on according with the selection. I don’t know whether i wrote it correct or not.
Thank you in advance for help.
var show = document.getElementById("show");
var select = document.getElementById("select");
if(select == "Boots"){
var newContent = document.createTextNode("You selected Boots");
show.appendChild(newContent);
}
else if(select == "Socks"){
var newContent2 = document.createTextNode("You selected Socks");
show.appendChild(newContent2);
}
else{
var newContent2 = document.createTextNode("You selected Tie");
show.appendChild(newContent2);
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>
<body>
<div class="container">
<p class="lead">Please Choose one in the following</p>
<form>
<select class="custom-select" id="select">
<option class="active">Choose one...</option>
<option>Boots</option>
<option>Socks</option>
<option>tie</option>
</select>
</form><br>
<p id="show" class="lead">
</p>
</div>
</body>
Solution
You will want to wrap your code inside the onchange
event handler so your code runs every time the selection changes. Then there is no need to keep appending child nodes every time the selection changes, simply set the innerHTML
of your show
element. Also unless you consider "tie"
to be the default value you may want to check for that:
Then you need to get the value of the selected item correctly. One way is to do select.options[select.selectedIndex].text
which will get the text value of the selected option
element.
var show = document.getElementById("show");
var select = document.getElementById("select");
select.onchange = function(){
value = select.options[select.selectedIndex].text;
if(value == "Boots"){
show.innerHTML = "You selected Boots";
}
else if(value == "Socks"){
show.innerHTML = "You selected Socks";
}
else if(value == "tie"){
show.innerHTML = "You selected Tie";
}
else {
show.innerHTML = "";
}
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>
<body>
<div class="container">
<p class="lead">Please Choose one in the following</p>
<form>
<select class="custom-select" id="select">
<option class="active">Choose one...</option>
<option>Boots</option>
<option>Socks</option>
<option>tie</option>
</select>
</form><br>
<p id="show" class="lead">
</p>
</div>
</body>
Answered By – Spencer Wieczorek
Answer Checked By – Marilyn (AngularFixing Volunteer)