使用javascript在其他下拉列表中根据所选值启用或禁用下拉列表

时间:2017-07-25 05:01:38

标签: javascript html html-select disabled-input

当我从下拉列表中选择Student选项时,我想从元素中删除属性。如果我选择TeacherStaff,课程和年级将停用,但如果我选择Student,则会启用感谢您的回复。< / p>

HTML:

<div class="control-group">
    <label class="control-label" for="inputPassword">Type:</label>
    <div class="controls">
        <select name="type" id="type" required>
            <option></option>
            <option>Student</option>
            <option>Teacher</option>
            <option>Staff</option>
            <option></option>
        </select>
    </div>
</div>

<div class="control-group">
    <label class="control-label" for="inputPassword">Course Type:</label>
    <div class="controls">
        <select name="course" id="course" required>
            <option></option>
            <option>BSIT</option>
            <option>BSCS</option>
            <option>BSHRM</option>
            <option>BSBM</option>
            <option>BSTM</option>
            <option>COE</option>
            <option></option>                                   
        </select>
    </div>
</div>

<div class="control-group">
    <label class="control-label" for="inputPassword">Year Level:</label>
    <div class="controls">
        <select name="year_level" id="year_level">
            <option> </option>
            <option>First Year</option>
            <option>Second Year</option>
            <option>Third Year</option>
            <option>Fourth Year</option>    
        </select>
    </div>
</div>

这是JavaScript:

<script>    
    document.getElementById('type').onchange = function () {  
        var obj = document.getElementById('course').setAttribute('disabled',this.value=='Student');

        document.getElementById('course').setAttribute('disabled',this.value=='Teacher');
        document.getElementById('year_level').setAttribute('disabled',this.value=='Teacher');

        obj.setAttribute('disabled');
        obj.removeAttribute('disabled');
    }    
</script>

下拉列表 drop-down print-screen

示例: https://jsfiddle.net/dzpr46d4/

1 个答案:

答案 0 :(得分:2)

要再次启用下拉菜单,您需要使用以下代码删除disabled属性:

document.getElementById('course').removeAttribute('disabled');

我有edited your JSFIDDLE DEMO。这是代码:

     document.getElementById('type').onchange = function () {
     alert("selected value = "+this.value);
     if(this.value == "Student")
     {
            document.getElementById('course').removeAttribute('disabled');
document.getElementById('year_level').removeAttribute('disabled');

     }
     else
     {
            document.getElementById('course').setAttribute('disabled', true);
                    document.getElementById('year_level').setAttribute('disabled', true);

     }
      }