1

我想使用 jQuery 验证我的表单。它有一组单选按钮。

我为一组单选按钮或解决方案找到了多种解决方案,您必须在其中具体说明有哪些组名。

像这里: 用 jquery 验证单选按钮?

问题是,表单是在运行时生成的。问题保存在 txt 文件中(不要问,这是学校练习)。生成的 HTML 代码如下所示:

<p>What&#039;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 生成的,因此可以循环遍历所有单选按钮组,但如果可能的话,我想避免这种情况。

4

2 回答 2

1

您需要先添加所有组(页面加载会很好,但请确保组数组在全局范围内),然后在提交表单/单击按钮时单独验证每个组

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);
    });
});
于 2012-11-05T09:06:55.877 回答
0

我让它像这样工作

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!

于 2012-11-05T10:02:24.317 回答