Html 多个具有相同名称的复选框的必需属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5884582/
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
Required attribute on multiple checkboxes with the same name?
提问by anna.mi
I have a list of checkboxes with the same nameattribute, and I need to validate that at least one of them has been selected.
我有一个具有相同名称属性的复选框列表,我需要验证是否至少选择了其中一个。
But when I use the html5 attribute "required" on all of them, the browser (chrome & ff) doesn't allow me to submit the form unless all of them are checked.
但是当我对所有这些都使用 html5 属性“required”时,浏览器(chrome & ff)不允许我提交表单,除非所有这些都被选中。
sample code:
示例代码:
<label for="a-0">a-0</label>
<input type="checkbox" name="q-8" id="a-0" required />
<label for="a-1">a-1</label>
<input type="checkbox" name="q-8" id="a-1" required />
<label for="a-2">a-2</label>
<input type="checkbox" name="q-8" id="a-2" required />
When using the same with radio inputs, the form works as expected (if one of the options is selected the form validates)
当与无线电输入使用相同时,表单按预期工作(如果选择了选项之一,则表单验证)
According to Joe Hopfgartner(who claims to quote the html5 specs), the supposed behaviour is:
根据Joe Hopfgartner(他声称引用了 html5 规范)的说法,假设的行为是:
For checkboxes, the required attribute shall only be satisfied when one or more of the checkboxes with that name in that form are checked.
For radio buttons, the required attribute shall only be satisfied when exactly one of the radio buttons in that radio group is checked.
对于复选框,仅选中该表单中该名称的一个或多个复选框时,才应满足所需的属性。
对于单选按钮,只有在检查该无线电组中的单选按钮之一时才应满足所需的属性。
am i doing something wrong, or is this a browser bug (on both chrome & ff) ??
我做错了什么,还是这是一个浏览器错误(在 chrome 和 ff 上)??
采纳答案by Erick Petrucelli
Sorry, now I've read what you expected better, so I'm updating the answer.
抱歉,现在我已经阅读了您期望的更好的内容,因此我正在更新答案。
Based on the HTML5 Specsfrom W3C, nothing is wrong. I created this JSFiddle testand it's behaving correctly based on the specs (for those browsers based on the specs, like Chrome 11 and Firefox 4):
基于W3C的HTML5 规范,没有任何问题。我创建了这个 JSFiddle 测试,它根据规范正确运行(对于那些基于规范的浏览器,如 Chrome 11 和 Firefox 4):
<form>
<input type="checkbox" name="q" id="a-0" required autofocus>
<label for="a-0">a-1</label>
<br>
<input type="checkbox" name="q" id="a-1" required>
<label for="a-1">a-2</label>
<br>
<input type="checkbox" name="q" id="a-2" required>
<label for="a-2">a-3</label>
<br>
<input type="submit">
</form>
I agree that it isn't very usable (in fact many people have complained about it in the W3C's mailing lists).
我同意它不是很有用(实际上很多人在W3C 的邮件列表中抱怨过它)。
But browsers are just following the standard's recommendations, which is correct. The standard is a little misleading, but we can't do anything about it in practice. You can always use JavaScript for form validation, though, like some great jQuery validation plugin.
但是浏览器只是遵循标准的建议,这是正确的。标准有点误导,但我们在实践中对此无能为力。不过,您始终可以使用 JavaScript 进行表单验证,就像一些出色的 jQuery 验证插件一样。
Another approach would be choosing a polyfillthat can make (almost) all browsers interpret form validation rightly.
另一种方法是选择一个填充工具,可以使(几乎)所有的浏览器解释表单验证正确。
回答by vantesllar
You can make it with jQuery a less lines:
您可以使用 jQuery 减少几行:
$(function(){
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
});
With $(':checkbox[required]')you select all checkboxes with the attribute required, then, with the .changemethod applied to this group of checkboxes, you can execute the functionyou want when any item of this group changes. In this case, if any of the checkboxes is checked, I remove the requiredattribute for all of the checkboxes that are part of the selected group.
使用$(':checkbox[required]')选择所有具有required属性的复选框,然后,将.change方法应用于这组复选框,当该组的任何项目发生更改时,您可以执行所需的功能。在这种情况下,如果选中任何复选框,我将删除属于所选组的所有复选框的required属性。
I hope this helps.
我希望这有帮助。
Farewell.
告别。
回答by fyrye
To provide another approach similar to the answer by @IvanCollantes.
It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked
checkbox.
提供另一种类似于@IvanCollantes 的答案的方法。它通过按名称额外过滤所需的复选框来工作。我还稍微简化了代码并检查了默认checked
复选框。
jQuery(function($) {
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.on('change', function(e) {
var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');
var isChecked = checkboxGroup.is(':checked');
checkboxGroup.prop('required', !isChecked);
});
requiredCheckboxes.trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form target="_blank">
<p>
At least one checkbox from each group is required...
</p>
<fieldset>
<legend>Checkboxes Group test</legend>
<label>
<input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1
</label>
<label>
<input type="checkbox" name="test[]" value="2" required="required">test-2
</label>
<label>
<input type="checkbox" name="test[]" value="3" required="required">test-3
</label>
</fieldset>
<br>
<fieldset>
<legend>Checkboxes Group test2</legend>
<label>
<input type="checkbox" name="test2[]" value="1" required="required">test2-1
</label>
<label>
<input type="checkbox" name="test2[]" value="2" required="required">test2-2
</label>
<label>
<input type="checkbox" name="test2[]" value="3" required="required">test2-3
</label>
</fieldset>
<hr>
<button type="submit" value="submit">Submit</button>
</form>
回答by Rommel Castro
i had the same problem, my solution was apply the required attribute to all elements
我遇到了同样的问题,我的解决方案是将 required 属性应用于所有元素
<input type="checkbox" name="checkin_days[]" required="required" value="0" /><span class="w">S</span>
<input type="checkbox" name="checkin_days[]" required="required" value="1" /><span class="w">M</span>
<input type="checkbox" name="checkin_days[]" required="required" value="2" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="3" /><span class="w">W</span>
<input type="checkbox" name="checkin_days[]" required="required" value="4" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="5" /><span class="w">F</span>
<input type="checkbox" name="checkin_days[]" required="required" value="6" /><span class="w">S</span>
when the user check one of the elements i remove the required attribute from all elements:
当用户检查其中一个元素时,我从所有元素中删除了 required 属性:
var $checkedCheckboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]:checked'),
$checkboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]');
$checkboxes.click(function() {
if($checkedCheckboxes.length) {
$checkboxes.removeAttr('required');
} else {
$checkboxes.attr('required', 'required');
}
});
回答by Zhomart
Here is improvement for icova's answer. It also groups inputs by name.
这是 icova 答案的改进。它还按名称对输入进行分组。
$(function(){
var allRequiredCheckboxes = $(':checkbox[required]');
var checkboxNames = [];
for (var i = 0; i < allRequiredCheckboxes.length; ++i){
var name = allRequiredCheckboxes[i].name;
checkboxNames.push(name);
}
checkboxNames = checkboxNames.reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
for (var i in checkboxNames){
!function(){
var name = checkboxNames[i];
var checkboxes = $('input[name="' + name + '"]');
checkboxes.change(function(){
if(checkboxes.is(':checked')) {
checkboxes.removeAttr('required');
} else {
checkboxes.attr('required', 'required');
}
});
}();
}
});
回答by Yukulélé
A little jQuery fix:
一个小的 jQuery 修复:
$(function(){
var chbxs = $(':checkbox[required]');
var namedChbxs = {};
chbxs.each(function(){
var name = $(this).attr('name');
namedChbxs[name] = (namedChbxs[name] || $()).add(this);
});
chbxs.change(function(){
var name = $(this).attr('name');
var cbx = namedChbxs[name];
if(cbx.filter(':checked').length>0){
cbx.removeAttr('required');
}else{
cbx.attr('required','required');
}
});
});
回答by OMA
Building on icova's answer, here's the code so you can use a custom HTML5 validation message:
以 icova 的回答为基础,这是代码,因此您可以使用自定义 HTML5 验证消息:
$(function() {
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function() {
if (requiredCheckboxes.is(':checked')) {requiredCheckboxes.removeAttr('required');}
else {requiredCheckboxes.attr('required', 'required');}
});
$("input").each(function() {
$(this).on('invalid', function(e) {
e.target.setCustomValidity('');
if (!e.target.validity.valid) {
e.target.setCustomValidity('Please, select at least one of these options');
}
}).on('input, click', function(e) {e.target.setCustomValidity('');});
});
});
回答by Marcos Alberton
var verifyPaymentType = function () {
//coloque os checkbox dentro de uma div com a class checkbox
var inputs = window.jQuery('.checkbox').find('input');
var first = inputs.first()[0];
inputs.on('change', function () {
this.setCustomValidity('');
});
first.setCustomValidity( window.jQuery('.checkbox').find('input:checked').length === 0 ? 'Choose one' : '');
}
window.jQuery('#submit').click(verifyPaymentType);
}