如何使用jQuery根据动态复选框的选中值启用新文本框
实现步骤
首先修正现有代码的两个小问题:
- 你当前代码中动态生成的选项是单选框(
type="radio"),如果需要复选框效果,把input标签的type属性改为type="checkbox"即可。 - 你现有初始化选中逻辑的选择器有误:动态生成的input的name统一为
DeptDetails,ID才是@itemName,所以原有$(':input[name="' + val + '"]')无法匹配到元素,建议改为$('#' + val),同时生成ID时注意过滤掉空格、特殊字符避免选择器报错。
以下是两种常用场景的实现方案,代码可直接加入你的<script>标签内:
场景1:选中任意复选框都启用/显示文本框
$(function() { // 给所有部门复选框绑定值变化事件 $('.cbxEmpDept').on('change', function() { // 判断是否存在已选中的复选框 const hasChecked = $('.cbxEmpDept:checked').length > 0; if (hasChecked) { // 显示文本框所在行,启用文本框 $('#trOtherDept').removeClass('hidden'); $('input[name="OtherDepartment"]').prop('disabled', false); // 如需调整为必填可开启下一行注释 // $('input[name="OtherDepartment"]').prop('required', true); } else { // 隐藏行,禁用并清空文本框 $('#trOtherDept').addClass('hidden'); $('input[name="OtherDepartment"]').prop('disabled', true).val(''); } }) // 页面初始化时触发一次事件,适配编辑页已有选中项的回显场景 $('.cbxEmpDept').trigger('change'); })
场景2:仅选中指定的某一个复选框(如「其他」选项)才启用文本框
$(function() { $('.cbxEmpDept').on('change', function() { // 此处判断逻辑可根据你的实际需求修改,例:判断选中的选项文本是否为「其他」 const isTargetChecked = $('.cbxEmpDept:checked').filter(function() { return $(this).next('span').text().trim() === '其他'; }).length > 0; if (isTargetChecked) { $('#trOtherDept').removeClass('hidden'); $('input[name="OtherDepartment"]').prop('disabled', false); } else { $('#trOtherDept').addClass('hidden'); $('input[name="OtherDepartment"]').prop('disabled', true).val(''); } }) $('.cbxEmpDept').trigger('change'); })
内容的提问来源于stack exchange,提问作者kamal
相关产品推荐
相关产品推荐

