Html 对一组复选框使用 HTML5“必需”属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6218494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using the HTML5 "required" attribute for a group of checkboxes?
提问by Zabba
When using the newer browsers that support HTML5 (FireFox 4 for example);
and a form field has the attribute required='required'
;
and the form field is empty/blank;
and the submit button is clicked;
the browsers detects that the "required" field is empty and does not submit the form;
instead browser shows a hint asking the user to type text into the field.
使用支持 HTML5 的较新浏览器时(例如 FireFox 4);
并且表单字段具有属性required='required'
;
并且表单字段为空/空白;
然后点击提交按钮;
浏览器检测到“必填”字段为空且不提交表单;
相反,浏览器会显示一个提示,要求用户在该字段中键入文本。
Now, instead of a single text field, I have a group of checkboxes, out of which at least one should be checked/selected by the user.
现在,我有一组复选框,而不是单个文本字段,其中至少一个应由用户检查/选择。
How can I use the HTML5 required
attribute on this group of checkboxes?
(Since only one of the checkboxes needs to be checked, I can't put the required
attribute on each and every checkbox)
如何required
在这组复选框上使用 HTML5属性?(由于只需要选中一个复选框,我不能将required
属性放在每个复选框上)
ps. I am using simple_form, if that matters.
附:如果这很重要,我正在使用simple_form。
UPDATE
更新
Could the HTML 5 multiple
attributebe helpful here? Has anyone use it before for doing something similar to my question?
可以在HTML 5multiple
的属性是有帮助吗?有没有人以前用它来做类似于我的问题的事情?
UPDATE
更新
It appearsthat this feature is not supported by the HTML5 spec:ISSUE-111: What does input.@required mean for @type = checkbox?
这似乎是这个功能不是HTML5规范的支持:ISSUE-111:什么输入@为@type =复选框需要的意思。?
(Issue status: Issue has been marked closed without prejudice.) And here is the explanation.
(问题状态:问题已无偏见地标记为已关闭。)这里是解释。
UPDATE 2
更新 2
It's an old question, but wanted to clarify that the original intent of the question was to be able to do the above without using Javascript - i.e. using a HTML5 way of doing it. In retrospect, I should've made the "without Javascript" more obivous.
这是一个老问题,但想澄清一下,这个问题的初衷是能够在不使用 Javascript 的情况下完成上述操作 - 即使用 HTML5 的方式。回想起来,我应该让“没有 Javascript”更明显。
采纳答案by Luca Fagioli
Unfortunately HTML5 does not provide an out-of-the-box way to do that.
不幸的是,HTML5 没有提供开箱即用的方式来做到这一点。
However, using jQuery, you can easily control if a checkbox group has at least one checked element.
但是,使用 jQuery,您可以轻松控制复选框组是否至少有一个选中的元素。
Consider the following DOM snippet:
考虑以下 DOM 片段:
<div class="checkbox-group required">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
</div>
You can use this expression:
你可以使用这个表达式:
$('div.checkbox-group.required :checkbox:checked').length > 0
which returns true
if at least one element is checked.
Based on that, you can implement your validation check.
true
如果至少检查了一个元素,则返回。基于此,您可以实施验证检查。
回答by thegauraw
Its a simple trick. This is jQuery code that can exploit the html5 validation by changing the required
properties if any one is checked. Following is your html code (make sure that you add required for all the elements in the group.)
这是一个简单的技巧。这是 jQuery 代码,它可以通过更改required
属性来利用 html5 验证,如果任何一个被选中。以下是您的 html 代码(确保您为组中的所有元素添加了 required 。)
<input type="checkbox" name="option[]" id="option-1" value="option1" required/> Option 1
<input type="checkbox" name="option[]" id="option-2" value="option2" required/> Option 2
<input type="checkbox" name="option[]" id="option-3" value="option3" required/> Option 3
<input type="checkbox" name="option[]" id="option-4" value="option4" required/> Option 4
<input type="checkbox" name="option[]" id="option-5" value="option5" required/> Option 5
Following is jQuery script, which disables further validation check if any one is selected. Select using name element.
以下是 jQuery 脚本,如果选择了任何一个,它将禁用进一步的验证检查。选择使用名称元素。
$cbx_group = $("input:checkbox[name='option[]']");
$cbx_group = $("input:checkbox[id^='option-']"); // name is not always helpful ;)
$cbx_group.prop('required', true);
if($cbx_group.is(":checked")){
$cbx_group.prop('required', false);
}
Small gotcha here: Since you are using html5 validation, make sure you execute this before the it gets validated i.e. before form submit.
这里有一个小问题:由于您使用的是 html5 验证,请确保在验证之前执行此操作,即在表单提交之前。
// but this might not work as expected
$('form').submit(function(){
// code goes here
});
// So, better USE THIS INSTEAD:
$('button[type="submit"]').on('click', function() {
// skipping validation part mentioned above
});
回答by Brian Woodward
HTML5 does not directly support requiring only one/at least one checkbox be checked in a checkbox group. Here is my solution using Javascript:
HTML5 不直接支持要求在复选框组中只选中一个/至少一个复选框。这是我使用 Javascript 的解决方案:
HTML
HTML
<input class='acb' type='checkbox' name='acheckbox[]' value='1' onclick='deRequire("acb")' required> One
<input class='acb' type='checkbox' name='acheckbox[]' value='2' onclick='deRequire("acb")' required> Two
JAVASCRIPT
爪哇脚本
function deRequireCb(elClass) {
el=document.getElementsByClassName(elClass);
var atLeastOneChecked=false;//at least one cb is checked
for (i=0; i<el.length; i++) {
if (el[i].checked === true) {
atLeastOneChecked=true;
}
}
if (atLeastOneChecked === true) {
for (i=0; i<el.length; i++) {
el[i].required = false;
}
} else {
for (i=0; i<el.length; i++) {
el[i].required = true;
}
}
}
The javascript will ensure at least one checkbox is checked, then de-require the entire checkbox group. If the one checkbox that is checked becomes un-checked, then it will require all checkboxes, again!
javascript 将确保至少选中一个复选框,然后取消整个复选框组的要求。如果选中的一个复选框未选中,那么它将再次需要所有复选框!
回答by Tyler Rick
I guess there's no standard HTML5 way to do this, but if you don't mind using a jQuery library, I've been able to achieve a "checkbox group" validation using webshims' "group-required" validation feature:
我想没有标准的 HTML5 方法可以做到这一点,但如果您不介意使用 jQuery 库,我已经能够使用webshims的“组需要”验证功能实现“复选框组”验证:
The docs for group-requiredsay:
If a checkbox has the class 'group-required' at least one of the checkboxes with the same name inside the form/document has to be checked.
如果复选框具有“group-required”类,则必须选中表单/文档中至少一个具有相同名称的复选框。
And here's an example of how you would use it:
这是一个如何使用它的示例:
<input name="checkbox-group" type="checkbox" class="group-required" id="checkbox-group-id" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
I mostly use webshims to polyfill HTML5 features, but it also has some great optional extensions like this one.
我主要使用 webshims 来填充 HTML5 功能,但它也有一些很棒的可选扩展,比如这个。
It even allows you to write your own custom validity rules. For example, I needed to create a checkbox group that wasn't based on the input's name, so I wrote my own validity rule for that...
它甚至允许您编写自己的自定义有效性规则。例如,我需要创建一个不基于输入名称的复选框组,因此我为此编写了自己的有效性规则......
回答by Passalini
I had the same problem and I my solution was this:
我遇到了同样的问题,我的解决方案是这样的:
HTML:
HTML:
<form id="processForm.php" action="post">
<div class="input check_boxes required wish_payment_type">
<div class="wish_payment_type">
<span class="checkbox payment-radio">
<label for="wish_payment_type_1">
<input class="check_boxes required" id="wish_payment_type_1" name="wish[payment_type][]" type="checkbox" value="1">Foo
</label>
</span>
<span class="checkbox payment-radio">
<label for="wish_payment_type_2">
<input class="check_boxes required" id="wish_payment_type_2" name="wish[payment_type][]" type="checkbox" value="2">Bar
</label>
</span>
<span class="checkbox payment-radio">
<label for="wish_payment_type_3">
<input class="check_boxes required" id="wish_payment_type_3" name="wish[payment_type][]" type="checkbox" value="3">Buzz
</label>
<input id='submit' type="submit" value="Submit">
</div>
</form>
JS:
JS:
var verifyPaymentType = function () {
var checkboxes = $('.wish_payment_type .checkbox');
var inputs = checkboxes.find('input');
var first = inputs.first()[0];
inputs.on('change', function () {
this.setCustomValidity('');
});
first.setCustomValidity(checkboxes.find('input:checked').length === 0 ? 'Choose one' : '');
}
$('#submit').click(verifyPaymentType);
回答by ewall
Inspired by the answers from @thegauraw and @Brian Woodward, here's a bit I pulled together for JQuery users, including a custom validation error message:
受到@thegauraw 和@Brian Woodward 的回答的启发,我为 JQuery 用户整理了一些内容,包括自定义验证错误消息:
$cbx_group = $("input:checkbox[name^='group']");
$cbx_group.on("click", function() {
if ($cbx_group.is(":checked")) {
// checkboxes become unrequired as long as one is checked
$cbx_group.prop("required", false).each(function() {
this.setCustomValidity("");
});
} else {
// require checkboxes and set custom validation error message
$cbx_group.prop("required", true).each(function() {
this.setCustomValidity("Please select at least one checkbox.");
});
}
});
Note that my form has some checkboxes checked by default.
请注意,我的表单默认选中了一些复选框。
Maybe some of you JavaScript/JQuery wizards could tighten that up even more?
也许你们中的一些 JavaScript/JQuery 向导可以进一步加强它?
回答by Juned Ansari
we can do this easily with html5 also, just need to add some jquery code
我们也可以用 html5 轻松做到这一点,只需要添加一些 jquery 代码
HTML
HTML
<form>
<div class="form-group options">
<input type="checkbox" name="type[]" value="A" required /> A
<input type="checkbox" name="type[]" value="B" required /> B
<input type="checkbox" name="type[]" value="C" required /> C
<input type="submit">
</div>
</form>
Jquery
查询
$(function(){
var requiredCheckboxes = $('.options :checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
} else {
requiredCheckboxes.attr('required', 'required');
}
});
});
回答by Codus
I added an invisible radio to a group of checkboxes. When at least one option is checked, the radio is also set to check. When all options are canceled, the radio is also set to cancel. Therefore, the form uses the radio prompt "Please check at least one option"
我在一组复选框中添加了一个隐形收音机。当至少一个选项被选中时,收音机也被设置为选中。取消所有选项后,收音机也设置为取消。因此,表单使用单选提示“请检查至少一个选项”
- You can't use
display: none
because radio can't be focused. - I make the radio size equal to the entire checkboxes size, so it's more obvious when prompted.
- 您无法使用,
display: none
因为收音机无法聚焦。 - 我使收音机大小等于整个复选框的大小,因此在提示时更明显。
HTML
HTML
<form>
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="radio-for-required-checkboxes" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
<input type="submit" value="submit"/>
</form>
Javascript
Javascript
var inputs = document.querySelectorAll('[name="option[]"]')
var radioForCheckboxes = document.getElementById('radio-for-checkboxes')
function checkCheckboxes () {
var isAtLeastOneServiceSelected = false;
for(var i = inputs.length-1; i >= 0; --i) {
if (inputs[i].checked) isAtLeastOneCheckboxSelected = true;
}
radioForCheckboxes.checked = isAtLeastOneCheckboxSelected
}
for(var i = inputs.length-1; i >= 0; --i) {
inputs[i].addEventListener('change', checkCheckboxes)
}
CSS
CSS
.checkboxs-wrapper {
position: relative;
}
.checkboxs-wrapper input[name="radio-for-required-checkboxes"] {
position: absolute;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
-webkit-appearance: none;
pointer-events: none;
border: none;
background: none;
}
回答by Abijith
Hi just use a text box additional to group of check box.When clicking on any check box put values in to that text box.Make that that text box required and readonly.
嗨,只需使用附加到复选框组的文本框。单击任何复选框时,将值放入该文本框。使该文本框必需且只读。
回答by Sean Kendle
I realize there are a ton of solutions here, but I found none of them hit every requirement I had:
我意识到这里有很多解决方案,但我发现它们都没有满足我的所有要求:
- No custom coding required
- Code works on page load
- No custom classes required (checkboxes or their parent)
- I needed several checkbox lists to share the same
name
for submitting Github issues via their API, and was using the namelabel[]
to assign labels across many form fields (two checkbox lists and a few selects and textboxes) - granted I could have achieved this without them sharing the same name, but I decided to try it, and it worked.
- 无需自定义编码
- 代码适用于页面加载
- 不需要自定义类(复选框或其父类)
- 我需要几个复选框列表来共享相同
name
的通过他们的 API 提交 Github 问题,并使用名称label[]
在许多表单字段(两个复选框列表和一些选择和文本框)中分配标签 - 当然我可以在没有他们共享的情况下实现这一目标同名,但我决定尝试一下,它奏效了。
The only requirement for this one is jQuery. You can combine this with @ewall's great solution to add custom validation error messages.
这个的唯一要求是 jQuery。您可以将其与@ewall 的出色解决方案结合使用,以添加自定义验证错误消息。
/* required checkboxes */
(function ($) {
$(function () {
var $requiredCheckboxes = $("input[type='checkbox'][required]");
/* init all checkbox lists */
$requiredCheckboxes.each(function (i, el) {
//this could easily be changed to suit different parent containers
var $checkboxList = $(this).closest("div, span, p, ul, td");
if (!$checkboxList.hasClass("requiredCheckboxList"))
$checkboxList.addClass("requiredCheckboxList");
});
var $requiredCheckboxLists = $(".requiredCheckboxList");
$requiredCheckboxLists.each(function (i, el) {
var $checkboxList = $(this);
$checkboxList.on("change", "input[type='checkbox']", function (e) {
updateCheckboxesRequired($(this).parents(".requiredCheckboxList"));
});
updateCheckboxesRequired($checkboxList);
});
function updateCheckboxesRequired($checkboxList) {
var $chk = $checkboxList.find("input[type='checkbox']").eq(0),
cblName = $chk.attr("name"),
cblNameAttr = "[name='" + cblName + "']",
$checkboxes = $checkboxList.find("input[type='checkbox']" + cblNameAttr);
if ($checkboxList.find(cblNameAttr + ":checked").length > 0) {
$checkboxes.prop("required", false);
} else {
$checkboxes.prop("required", true);
}
}
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="post.php">
<div>
Type of report:
</div>
<div>
<input type="checkbox" id="chkTypeOfReportError" name="label[]" value="Error" required>
<label for="chkTypeOfReportError">Error</label>
<input type="checkbox" id="chkTypeOfReportQuestion" name="label[]" value="Question" required>
<label for="chkTypeOfReportQuestion">Question</label>
<input type="checkbox" id="chkTypeOfReportFeatureRequest" name="label[]" value="Feature Request" required>
<label for="chkTypeOfReportFeatureRequest">Feature Request</label>
</div>
<div>
Priority
</div>
<div>
<input type="checkbox" id="chkTypeOfContributionBlog" name="label[]" value="Priority: High" required>
<label for="chkPriorityHigh">High</label>
<input type="checkbox" id="chkTypeOfContributionBlog" name="label[]" value="Priority: Medium" required>
<label for="chkPriorityMedium">Medium</label>
<input type="checkbox" id="chkTypeOfContributionLow" name="label[]" value="Priority: Low" required>
<label for="chkPriorityMedium">Low</label>
</div>
<div>
<input type="submit" />
</div>
</form>