如何在jQuery选择器中包含text、radio、checkbox等所有类型的input元素
表单提交按钮适配radio/checkbox校验方案
你当前使用的.field input选择器已经可以覆盖radio、checkbox类型的input元素,不需要额外调整选择器,只需要修改事件绑定和校验逻辑即可适配这两类输入。
核心修改点
- 事件绑定新增
change类型,覆盖单选、复选框的点击选择场景 - 调整字段校验逻辑,针对不同输入类型做适配判断
- 修复原遍历逻辑的判断错误:只要存在任意未完成的输入项,就保持提交按钮禁用
- 优化布尔属性操作:改用
prop()方法操作disabled属性,比attr()兼容性更好
完整修改后代码
JavaScript代码
$(document).ready(function() { // 同时绑定keyup和change事件,覆盖所有输入场景 $('.field input').on('keyup change', function() { let hasEmpty = false; $('.field input').each(function() { const $input = $(this); // 针对单选、复选框做单独判断 if ($input.is(':radio, :checkbox')) { // 同name单选组只要有一个选中即判定为有效 if ($input.is(':radio')) { const groupName = $input.attr('name'); if ($(`input[name="${groupName}"]:checked`).length === 0) { hasEmpty = true; // 只要找到一个未完成项就终止遍历 return false; } } else { // 复选框判定自身是否选中 if (!$input.is(':checked')) { hasEmpty = true; return false; } } } else { // 普通文本类输入判断值是否非空,trim避免空格误判 if ($input.val().trim().length === 0) { hasEmpty = true; return false; } } }); // 用prop操作disabled布尔属性更稳定 $('.actions input[type="submit"]').prop('disabled', hasEmpty); }); });
带单选、复选框的HTML示例
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div class='form'> <form> <div class='field'> <label for="username">用户名</label> <input id="username" type="text" /> </div> <div class='field'> <label for="password">密码</label> <input id="password" type="password" /> </div> <!-- 新增单选框组 --> <div class='field'> <label>性别</label> <input type="radio" name="gender" value="male"> 男 <input type="radio" name="gender" value="female"> 女 </div> <!-- 新增复选框 --> <div class='field'> <input type="checkbox" id="agree"> <label for="agree">同意用户协议</label> </div> <div class='actions'> <input type="submit" value="登录" disabled="disabled" /> </div> </form> </div>
内容的提问来源于stack exchange,提问作者pomchips
相关产品推荐
相关产品推荐

