干得好
change
事件侦听复选框的更改,我使用"#checkbox"
指定。使用change
非常重要,因此您可以切换disable
属性。
.attr("disabled", true);
添加了disabled
属性。假的恰恰相反。
$("#checkbox").change(function() {
if(this.checked) {
$("#end-month").attr("disabled", true);
} else {
$("#end-month").attr("disabled", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="checkbox" type="checkbox">
<label for="checkbox">I am currently working here</label>
<br>
<select id="end-month">
<option value="date">date</option>
<option value="another-date">another date</option>
</select>
禁用id中的所有元素,这些元素位于data-disable属性中。如果你想隐藏,请使用注释代码而不是dest.attr()。
$("input[type='checkbox'][data-disable]").on("click", function () {
var dest = $("#" + $(this).data("disable")).find(":input");
if ($(this).is(':checked')) {
dest.attr("disabled", "disabled");
//dest.hide();
} else {
dest.attr("disabled", false);
//dest.show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label><input type="checkbox" data-disable="idToHide"/> Disable</label>
<div id="idToHide">
<select><option>test</option></select>
</div>
</form>
如果您使用表单和输入,解决方案不必是jQuery,您只需在输入中添加disabled
属性即可。
https://codepen.io/limxz/pen/XQdPXO
以下是一些参考资料。 https://www.w3schools.com/tags/att_select_disabled.asp
这是一个没有jQuery的简化演示
var checkboxInput = document.querySelector("#checkbox-input");
var dropdownInput = document.querySelector("#dropdown-input");
checkboxInput.addEventListener("change", function(e) {
e.preventDefault();
if (checkboxInput.value) {
dropdownInput.setAttribute("disabled", "");
}
});