简体   繁体   中英

Show/hide div according to select option in javascript

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?

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';
};

You may get value of selected option like below:

JSFIDDLE

<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>

try this

 studentDiv.style.display = (this.value==="student") ? 'block':'none';
 teacherDiv.style.display = (this.value==="teacher") ? 'block':'none';

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM