Reputation: 1737
Searched the internet. Learnt how to do this. Implemented it. But it doesn't work. I want to show the div student when student is selected and the div teacher when teacher is selected. This is a part of a jsp file.
HTML code :
<table>
<tr>
<td>
<select id="userType">
<option value="student">STUDENT</option>
<option value="teacher">TEACHER</option>
<option value="admin">ADMIN</option>
</select>
</td>
</tr>
<table>
Javascript code:
<script type="text/javascript">
var elem = document.getElementById('userType');
elem.onchange = function() {
var studentDiv = document.getElementById('student');
var teacherDiv = document.getElementById('teacher');
studentDiv.style.display = (this.value.equals("student")) ? 'block':'none';
teacherDiv.style.display = (this.value.equals("teacher")) ? 'block':'none';
};
</script>
I've been trying to get this right since morning. Tried other methods as well. Nothing works. What am I doing wrong?
Upvotes: 1
Views: 278
Reputation: 3466
Two problems immediately pop out:
You are trying to select items that do not have id's defined. You are calling a non-existent ".value" on the element value property.
These errors will be reported in your browser developer tools. Use them.
Upvotes: 0
Reputation: 600
try this
studentDiv.style.display = (this.value==="student") ? 'block':'none';
teacherDiv.style.display = (this.value==="teacher") ? 'block':'none';
Upvotes: 0
Reputation: 122155
Change equals
to ==
in your code and it works DEMO
var elem = document.getElementById('userType');
elem.onchange = function() {
var studentDiv = document.getElementById('student');
var teacherDiv = document.getElementById('teacher');
studentDiv.style.display = (this.value == "student") ? 'block' : 'none';
teacherDiv.style.display = (this.value == "teacher") ? 'block' : 'none';
};
Upvotes: 2
Reputation: 2124
You may get value of selected option like below:
<script type="text/javascript">
var elem = document.getElementById('userType');
elem.onchange = function() {
var studentDiv = document.getElementById('student');
var teacherDiv = document.getElementById('teacher');
studentDiv.style.display = this.options[this.selectedIndex].value == "student" ? 'block':'none';
teacherDiv.style.display = this.options[this.selectedIndex].value == "teacher" ? 'block':'none';
};
</script>
Upvotes: 0