jQuery实现选中复选框时为对应关联输入框设置required必填
实现方案
原代码存在两处核心问题:一是错误给所有同组复选框绑定了required校验逻辑,二是没有建立复选框和对应位置文本输入框的关联,无法触发输入框的必填校验。修正逻辑如下:
- 移除所有复选框原生的required属性,互斥单选场景下不需要给复选框本身添加必填校验
- 点击复选框时,先重置同组所有对应输入框的required状态,取消其他同组复选框的选中状态
- 若当前点击的复选框为选中状态,定位到它对应的文本输入框,给该输入框添加required属性
- 修正原HTML中重复ID的问题,保证每个元素ID唯一,符合HTML规范
修正后JS代码
$(document).ready(function() { $('.check').click(function() { const groupName = $(this).attr("name"); const $groupChecks = $('.check[name="' + groupName + '"]'); // 重置同组所有输入框的必填状态 $groupChecks.each(function() { $(this).nextAll('input[type="text"]:first').prop('required', false); }); // 同组复选框互斥,取消其他项选中 $groupChecks.not(this).prop('checked', false); // 当前项选中时,给对应输入框添加必填校验 if ($(this).prop('checked')) { $(this).nextAll('input[type="text"]:first').prop('required', true); } }); });
修正后HTML代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="OVD-passport" name="OVD" class="check"> <h5>A. 护照号码</h5> <input type="text"><br> <input type="checkbox" id="OVD-voter" name="OVD" class="check"> <h5>B. 选民身份证</h5> <input type="text"><br> <input type="checkbox" id="OVD-dl" name="OVD" class="check"> <h5>C. 机动车驾驶证</h5> <input type="text"><br> <input type="checkbox" id="OVD-nrega" name="OVD" class="check"> <h5>D. NREGA就业卡</h5> <input type="text"><br> <input type="checkbox" id="OVD-npr" name="OVD" class="check"> <h5 class="d-inline">E. 全国人口登记证明信</h5> <input type="text"><br> <input type="checkbox" id="OVD-aadhaar" name="OVD" class="check"> <h5 class="d-inline">F. 阿达哈尔(Aadhaar)身份持有证明</h5> <input type="text">
代码说明:通过
nextAll('input[type="text"]:first')定位复选框对应的输入框,不受中间间隔的h5标签影响,可以准确匹配每个复选框后方紧邻的第一个文本输入框。
内容的提问来源于stack exchange,提问作者Md Mohtesham Azam
相关产品推荐
相关产品推荐

