2012-07-13 187 views
0

我有一个包含多个问题的表单(一个动态创建的问卷)。我已经使用jQuery的样式的收音机作为按钮(http://jqueryui.com/demos/button/#radio),但我已经砍下代码稍有这里...使用jQuery验证单选按钮

<div class="yesnoradios"> 
    <input type="radio" name="section<%= section %>_question<%= question %>" id="section<%= section %>_question<%= question %>_Y" value="Y" />Yes 
    <input type="radio" name="section<%= section %>_question<%= question %>" id="section<%= section %>_question<%= question %>_N" value="N" />No 
    <input type="radio" name="section<%= section %>_question<%= question %>" id="section<%= section %>_question<%= question %>_NA" value="NA" />N/A 
</div> 

所以,我有上述的多个实例,动态命名为id's。

我正在努力向客户端验证提交表单。我需要做的是确保为每个问题选择一个答案。我没有很多jQuery的经验,所以我到目前为止所做的每个问题都是循环的。

$('.yesnoradios').each(function(index) { 
    alert($(this).attr("id")); 
}); 

我想我会提到,在英语中查看网页时,它使用select的,而不是单选按钮,我能确认很好,但我之所以不能使用,在这个实例是用户正在用一种语言查看页面,其中“是”或“否”的等效取决于您如何构建问题,因此我使用了蜱和十字。

在此先感谢您的帮助。

编辑:我试图做的是使用.children()函数来检查是否检查一个,如果没有设置一个标志,说明窗体无效。但是我无法获得正确的语法,并且还没有找到一个好的代码示例。

+1

可能为时已晚,但[此插件](http://elclanrs.github.com/jq-idealforms/)可以提供帮助。 – elclanrs 2012-07-13 09:59:34

+0

好看的插件。肯定会在未来的项目中使用它。谢谢。 – 2012-07-13 10:02:09

回答

4

假设你有很多的下方...

<div class="yesnoradios"> 
    <input type="radio" name="section<%= section %>_question<%= question %>" id="section<%= section %>_question<%= question %>_Y" value="Y" />Yes 
    <input type="radio" name="section<%= section %>_question<%= question %>" id="section<%= section %>_question<%= question %>_N" value="N" />No 
    <input type="radio" name="section<%= section %>_question<%= question %>" id="section<%= section %>_question<%= question %>_NA" value="NA" />N/A 
</div> 

您可以使用它来查看是否至少有一个组被选中使用以下代码

$('.yesnoradios input[type=radio]:checked').length 

这会给你确切的检查组号。与没有class="yesnoradios"检查它,如果你有一样没有然后在每个yesnoradio DIV的无线电装置中的至少一个已经被检查

if($('.yesnoradios').length == $('.yesnoradios input[type=radio]:checked').length){ 
    //all groups have at least one radio checked 
}else{ 
    //not all are chedked and you can loop your else logic here 
} 

注:所有你在一组无线电应该有相同的名称。 ..因为你在这里发布了未被渲染的html,我会假设它是这样做的。

+0

嗨LoneWOLFs,是的,他们都有相同的名称。感谢代码片段,会给你一个尝试。 – 2012-07-13 10:12:01

+0

@GarethLewis做到了吗? – LoneWOLFs 2012-07-13 10:28:09

+0

是的,它确实工作。非常感谢您的帮助。 – 2012-07-13 13:59:40

3
if ($('input[name='+ radioName +']:checked').length) { 
      // at least one of the radio buttons was checked 
      return true; // allow whatever action would normally happen to continue 
     } 
     else { 
      // no radio button was checked 
      return false; // stop whatever action would normally happen 
     } 
+0

这不会检查是否所有的yesnoradio类都被验证了......他必须在循环中检查所有的div。 – LoneWOLFs 2012-07-13 10:39:12

0

试试这个。你的HTML应该像

radio buttons with class "optionCls" in a div with id question1 
radio buttons with class "optionCls" in a div with id question2 
. 
. 

现在,你可以参考它像

if($('#question1.optionCls :checked').length() > 0) 
    alert('valid'); //will tell you for question1 whether answer is selected or not 

建立你的逻辑,使其动态