使用jQuery依据父子单选按钮状态控制提交按钮禁用状态的问题咨询
问题原因
原有实现只监听了子单选按钮的点击事件,没有处理父级单选切换的场景:切换父级单选时,不会清空之前选中的子单选状态,也不会重新禁用提交按钮,导致逻辑不符合预期。
修复方案
调整逻辑
- 新增父级单选按钮的点击监听,切换父级时清空所有子单选的选中状态,同时禁用提交按钮
- 子单选点击时新增校验逻辑,仅当所属父级处于选中状态时,才启用提交按钮
完整可运行代码
JS 部分
// 监听父级单选按钮点击 $('.checkbox-parent').on('click', function() { // 清空所有子单选选中状态 $('.checkbox-child').prop('checked', false); // 选中父级时默认禁用提交按钮 $('.submit-button').attr('disabled', true); }); // 监听子级单选按钮点击 $('.checkbox-child').on('click', function() { // 校验当前子单选所属的父级是否处于选中状态 const isParentChecked = $(this).closest('.item-container').find('.checkbox-parent').is(':checked'); if (isParentChecked) { $('.submit-button').removeAttr('disabled'); } });
CSS 部分(原有逻辑无需修改)
.submit-button{ background-color:red; border:none; padding:10px 20px; color:white; } .submit-button:disabled{ background-color: grey !important; } .checkbox-child-wrapper{ margin-left:20px; }
HTML 部分(原有逻辑无需修改)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="checkbox-container"> <div class="item-container" id="parent-1"> <input type="radio" name="check-parent" class="checkbox-parent"> Parent 1 <div class="checkbox-child-wrapper"> <input type="radio" name="check-child" class="checkbox-child"> Child 1 <input type="radio" name="check-child" class="checkbox-child"> Child 2 <input type="radio" name="check-child" class="checkbox-child"> Child 3 </div> </div> <div class="item-container" id="parent-2"> <input type="radio" name="check-parent" class="checkbox-parent"> Parent 2 <div class="checkbox-child-wrapper"> <input type="radio" name="check-child" class="checkbox-child"> Child 1 <input type="radio" name="check-child" class="checkbox-child"> Child 2 <input type="radio" name="check-child" class="checkbox-child"> Child 3 </div> </div> </div> <button class="submit-button" disabled>Submit</button>
内容的提问来源于stack exchange,提问作者fikfe
相关产品推荐
相关产品推荐

