如何使用jQuery仅在隐藏字段激活时执行表单验证
问题修复方案
你当前代码存在两个影响校验逻辑的问题:
- 下拉选择框与自定义输入框
name属性重名,提交时会发生值覆盖 - 隐藏的自定义输入框未做状态隔离,无法实现「仅显示时校验」的需求
实现逻辑
利用表单原生规则:被设置disabled属性的字段不会参与提交、也不会触发原生校验。切换下拉选项时,同步控制自定义输入框的显隐、禁用状态、必填属性即可:
- 选中「others」时:显示输入框,移除
disabled,添加required校验,自动聚焦 - 选中其他选项时:隐藏输入框,添加
disabled,移除required,清空残留输入值
完整修正代码
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script type="text/javascript"> function checkvalue(val) { const customColorInput = document.getElementById('custom_color'); if(val==="others"){ customColorInput.style.display='block'; customColorInput.disabled = false; customColorInput.required = true; customColorInput.focus(); } else { customColorInput.style.display='none'; customColorInput.disabled = true; customColorInput.required = false; customColorInput.value = ''; } } </script> </head> <body> <div class="container"> <form action="" class="signin-form"> <div class="form-group"> <select name="color" onchange='checkvalue(this.value)' required> <option value="">pick a color</option> <option value="red">RED</option> <option value="blue">BLUE</option> <option value="others">others</option> </select> </div> <div class="form-group"> <input type="text" name="custom_color" id="custom_color" class="form-control" style='display:none' disabled placeholder="Input your custom color"/> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </body> </html>
补充说明
- 给默认占位选项
pick a color添加了空值value="",配合select标签上的required属性,实现下拉框必选校验,避免用户直接选占位项提交 - 初始状态下自定义输入框默认加了
disabled属性,页面首次加载时不会触发该字段的校验 - 如果需要提交时统一颜色字段值(选others时取自定义输入内容,否则取下拉选项值),可以在表单submit事件中自行组装字段即可
内容的提问来源于stack exchange,提问作者Deepu
相关产品推荐
相关产品推荐

