Validating check boxes in HTML(验证 HTML 中的复选框)
问题描述
我有一个表格,有 4 个选项(可能是复选框或单选).
I have a form there are 4 options (they may be checkbox or radio).
我想选择多个选项,但必须选择一个.
I want to select multiple options but one is compulsory.
我知道这在 JS/jQuery 中是可能的,但我想要一个基于 HTML/CSS 的解决方案.
I know it is possible in JS/jQuery but I want a HTML/CSS based solution.
推荐答案
为了能够检查多个输入,它们必须是复选框.(它们可能是具有不同名称的单选按钮,但一旦选中,您将无法取消选中它们.)
To be able to check multiple inputs, they must be checkboxes. (They could be radio buttons with different names, but you wouldn't be able to uncheck them once checked.)
因此,请使用复选框,并仅在选中时显示提交按钮,使用 通用兄弟选择器 (~):
So use checkboxes, and show the Submit button only if any are checked, using the general sibling selector (~):
input[type="Submit"] {
display: none;
}
input:checked ~ input[type="Submit"] {
display: inline;
}
<input id="c1" type="checkbox"><label for="c1">First</label><br>
<input id="c2" type="checkbox"><label for="c2">Second</label><br>
<input id="c3" type="checkbox"><label for="c3">Third</label><br>
<input id="c4" type="checkbox"><label for="c4">Fourth</label><br>
<input type="Submit">
<小时>如果您希望显示禁用的提交按钮,请添加第二个禁用的按钮.
If you want the appearance of a disabled submit button, add a second button that is disabled.
当没有点击输入时,只显示禁用的提交按钮.单击一个或多个输入时,仅显示启用的提交按钮:
When no input is clicked, show the disabled submit button only. When one or more inputs are clicked, show the enabled submit button only:
input[type="Submit"]:not([disabled]) {
display: none;
}
input:checked ~ input[type="Submit"]:not([disabled]) {
display: inline;
}
input:checked ~ input[disabled] {
display: none;
}
<input id="c1" type="checkbox"><label for="c1">First</label><br>
<input id="c2" type="checkbox"><label for="c2">Second</label><br>
<input id="c3" type="checkbox"><label for="c3">Third</label><br>
<input id="c4" type="checkbox"><label for="c4">Fourth</label><br>
<input type="Submit" disabled>
<input type="Submit">
这篇关于验证 HTML 中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:验证 HTML 中的复选框
基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
