[英]Validate radio buttons with jQuery on submit
我想使用jQuery验证我的表单。 它具有单选按钮组。
对于单个单选按钮或解决方案组,我发现了多种解决方案,您必须在其中特别说明存在哪些组名。
就像这里: 用jquery验证单选按钮?
问题在于,该表单是在运行时生成的。 问题将保存在txt文件中(不要问,这是学校的练习)。 生成的HTML代码如下所示:
<p>What's your gender?
<input type="radio" name="gender" value="m" />Male
<input type="radio" name="gender" value="f" />Female
</p>
<p>
How satisfied are you with out support?
<input type="radio" name="satisfaction" value="0%" />Not at all
<input type="radio" name="satisfaction" value="25%" />Not very much
<input type="radio" name="satisfaction" value="75%" />It was ok
<input type="radio" name="satisfaction" value="100% />It was very satisfying
</p>
该js文件是使用Twig生成的,因此可以遍历所有单选按钮组,但我想避免这种情况。
您需要先添加所有组(页面加载会很好,但要确保组数组在全局范围内),然后在提交表单/单击按钮时分别验证每个组
var groups = [];
$(function() {
$("input[type=radio][name]").each(function() {
// Add the unique group name to the array
groups[$(this).attr("name")] = true;
});
});
$("button").click(function() {
$.each(groups, function(i, o) {
// For each group, check at least one is checked
var isValid = $("input[name='"+i+"']:checked").length;
alert(i + ": " + isValid);
});
});
我像这样工作
var groups = [];
$(function() {
$("input[type=radio][name]").each(function() {
// Add the unique group name to the array
if (groups[groups.length - 1] != $(this).attr("name")) groups.push($(this).attr("name"));
});
});
$('form').submit(function () {
var isValid = true;
$.each(groups, function(i, o) {
// For each group, check at least one is checked
if (isValid) isValid = $("input[name='"+o+"']:checked").length;
});
if (!isValid) return false;
return true;
});
感谢Blade0rz!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.