Forum Moderators: open
Im new to javascript / ajax which is evident. Im trying to show hide divs based on the selected option in a select menu. Here's what I have:
function updateEvents() {
var events = document.getElementById("displayevents").value;
if (events == 'b') {
document.getElementById("day").style.display = 'block';
document.getElementById("weekend").style.display = 'none';
}
if (events == 'c') {
document.getElementById("day").style.display = 'none';
document.getElementById("weekend").style.display = 'block';
}
else {
document.getElementById("day").style.display = 'block';
document.getElementById("weekend").style.display = 'block';
}
}
This isn't working, can anyone help?
Thanks in advance
<select name="displayevents" id="displayevents" onChange="updateEvents();">
What is happening is you are referencing the selected options's value incorrectly which could have been found by adding alert(event) in the function. You get at the selected option value by referencing the selectedIndex. But here's an easier way: you use the this keyword to pass the select object's value itself to the function. Note how "event" is now a passed parameter, no need to get it's selected index and value in the function.....
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Update Events</title>
<script type="text/javascript">
function updateEvents(events) {
var day = document.getElementById('day'); // The day div OBJECT
var weekend = document.getElementById('weekend'); // the weekend div OBJECT
day.style.display = ((events=='b') ¦¦ (events==''))?'block':'none'; // Assign style
weekend.style.display = ((events=='b') ¦¦ (events==''))?'none':'block'; //properties to the objects
}
</script>
</head>
<body>
<div id="somediv">
<form>
<select name="displayevents" id="displayevents"
onChange="updateEvents(this[this.selectedIndex].value);">
<option value="">Select</option>
<option value="b">Bee</option>
<option value="c">Cee</option>
</select>
</form>
</div>
<div id="day" style="display:block;"> Day</div>
<div id="weekend" style="display:none;"> Weekend</div>
</body>
</html>
NOTE: The ¦ represents the UNBROKEN vertical pipe, the logical "or" operator.