我遇到了一个问题。如果我在select标签中选择了多个项目,并在删除选择项时再次将其禁用,如何启用禁用的输入?
<div class="form-group mb-3">
<select class="selectpicker show-tick decore" name="state" id="state" multiple>
<option value="one">one</option>
<option value="two">two</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">
<i class="fas fa-child"></i>
</span>
</div>
<input type="text" name="first" id="first" class="form-control" placeholder="first" aria-label="first" aria-describedby="basic-addon1" disabled />
</div>
<input type="text" name="second" id="second" class="form-control" placeholder="second" aria-label="second" aria-describedby="basic-addon1" disabled />
</div>
答案 0 :(得分:4)
对change
标签使用select
事件处理程序,并在函数中检查selected
选项的长度是否小于2
删除disabled
属性,如果是比2
更好地将其添加到元素中。
document.getElementById("state").onchange = function(){
var length = this.querySelectorAll("option:checked").length;
document.querySelectorAll("#first, #second").forEach(function(ele){
ele.disabled = length < 2;
})
}
document.getElementById("state").onchange = function(){
var length = this.querySelectorAll("option:checked").length;
document.querySelectorAll("#first, #second").forEach(function(ele){
ele.disabled = length < 2;
})
}
<div class="form-group mb-3">
<select class="selectpicker show-tick decore" name="state" id="state" multiple>
<option value="one">one</option>
<option value="two">two</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">
<i class="fas fa-child"></i>
</span>
</div>
<input type="text" name="first" id="first" class="form-control" placeholder="first" aria-label="first" aria-describedby="basic-addon1" disabled />
<input type="text" name="second" id="second" class="form-control" placeholder="second" aria-label="second" aria-describedby="basic-addon1" disabled />
</div>
您还可以使用 jQuery 并以更少的代码完成这项工作
$("#state").change(function(){
$("#first, #second").prop("disabled", $(":selected",this).length < 2);
});
$("#state").change(function(){
$("#first, #second").prop("disabled", $(":selected",this).length < 2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group mb-3">
<select class="selectpicker show-tick decore" name="state" id="state" multiple>
<option value="one">one</option>
<option value="two">two</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">
<i class="fas fa-child"></i>
</span>
</div>
<input type="text" name="first" id="first" class="form-control" placeholder="first" aria-label="first" aria-describedby="basic-addon1" disabled />
<input type="text" name="second" id="second" class="form-control" placeholder="second" aria-label="second" aria-describedby="basic-addon1" disabled />
</div>