You can get the selected value by using "value" method on "select" element object. For below html you can get the value of select tag by document.getElementById("color").value
<body>
<select id="color">
<option value="red">red</option>
<option value="blue">blue</option>
</select>
<div id="red" style="display:none;">
<p>You want RED</p>
</div>
<div id="blue" style="display:none;">
<p>You want BLUE</p>
</div>
</body>
Heres how I have written my js :
<script>
window.addEventListener("load", function() {
document.getElementById("color").addEventListener("change", function() {
var selectElem = document.getElementById("color");
document.getElementById("red").style.display = "none";
document.getElementById("blue").style.display = "none";
document.getElementById(selectElem.value).style.display = "block";
})
})
</script>
Tip : Always try to implement DRY(Dont repeat your code) code.
The above code will not work in IE8 or below. IE8 and below browsers supports attachEvent() method. We can create our own custom event handler method that will work for cross browsers.
function addHandler(element, type, handler) {
alert("Hi");
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else if(element.attachEvent) {
element.attachEvent("on"+type, handler)
} else {
element["on"+type] = handler };
}
addHandler(window, "load", main)
function main() {
function handler() {
var selectElem = document.getElementById("color");
document.getElementById("red").style.display = "none";
document.getElementById("blue").style.display = "none";
document.getElementById(selectElem.value).style.display = "block";
}
addHandler(document.getElementById("color"), "change", handler);
}
I have created a custom addHandler() function that will work for all IE's, chrome, firefox, opera and safari.