Reputation: 797
I try to write simple JS switch which will display content based on selection, so lets say i will have html doc with 4 div's if user will select option one div one will be displayed etc.
Here is fast draft which i made but it don't work. Can you please help me understand what i'm doing wrong here ?
HTML
<legend>Selecting elements</legend>
<p>
<label>Select list</label>
<select id = "myList">
<option value = "1">one</option>
<option value = "2">two</option>
<option value = "3">three</option>
<option value = "4">four</option>
</select>
</p>
</fieldset>
<p id ="demo"></p>
JS
function myfunction () {
var text;
var city = getElementById("myList").value;
switch(city) {
case "one":
text ="test one";
break;
case "two":
text ="test two";
break;
case "three":
text ="test three";
break;
case "four":
text = "test four";
break;
default:
text = " ";
}
document.getElementById("demo").innerHTML = text;
}
Upvotes: 0
Views: 1673
Reputation: 3047
onchange="myfunction()"
add this for call your function
Upvotes: 1
Reputation: 388326
There are few issues with the code
function myfunction() {
var text;
var city = document.getElementById("myList").value; //need to use document.getElementById()
switch (city) {
//the select values are 1, 2, 3 not one, two etc
case "1":
text = "test one";
break;
case "2":
text = "test two";
break;
case "3":
text = "test three";
break;
case "4":
text = "test four";
break;
default:
text = " ";
}
document.getElementById("demo").innerHTML = text;
}
<legend>Selecting elements</legend>
<p>
<label>Select list</label>
<!--Need to call myfunction on change of the select-->
<select id="myList" onchange="myfunction()">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</p>
</fieldset>
<p id="demo"></p>
If you just want to show a predefined text then
var mymap = {
1: "test one",
2: 'test two',
3: 'test three',
4: 'test four'
}
function myfunction() {
var city = document.getElementById("myList").value; //need to use document.getElementById()
var text = mymap[city] || ' ';
document.getElementById("demo").innerHTML = text;
}
<legend>Selecting elements</legend>
<p>
<label>Select list</label>
<!--Need to call myfunction on change of the select-->
<select id="myList" onchange="myfunction()">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</p>
</fieldset>
<p id="demo"></p>
Upvotes: 1