2011-01-25 65 views
1

我一直在绞尽脑汁寻找更好的解决方案来处理以下情况。使用jquery查找没有答案的单选按钮组

想象一下其上有许多单选按钮的页面,然后进行一些自定义验证,突出显示未被回答的单选按钮组。

例如HTML(与预选的一些答案):

<input type='radio' name='a' value='1' /> 
<input type='radio' name='a' value='2' /> 
<input type='radio' name='a' value='3' /> 
<input type='radio' name='b' value='1' checked="checked"//> 
<input type='radio' name='b' value='2' /> 
<input type='radio' name='b' value='3' /> 
<input type='radio' name='c' value='1' /> 
<input type='radio' name='c' value='2' checked="checked"/> 
<input type='radio' name='c' value='3' /> 
<input type='radio' name='d' value='1' /> 
<input type='radio' name='d' value='2' /> 
<input type='radio' name='d' value='3' /> 

我已经写了jQuery的一点那我想要做什么,但我只知道这是可以做到更好/更快/更漂亮/多有效率的。

//select all radiobuttons 
var $radios = $("input[type='radio']") 
//loop through all the radios that are checked 
$($radios+":checked").each(function(){ 
    //filter out all radios with the current name, and add something to recognize them with 
    $($radios).filter("[name='" + $(this).attr("name") + "']").addClass("checked") 
}); 

//find all radios without the class checked, and highlight them 
var $unchecked_radios = $($radios + ":not(.checked)").addClass("highlight"); 

但我坚持如何结合这两个,所以减去那些从整个无线电人口有答案的。

(虽然我怀疑有可能是一个更好的方式来选择具有相同名称的单选按钮组)

任何帮助将不胜感激!

问候, 卡斯帕

+0

对象“{a:false,b:true,c:true,d:false}”是否适合您? – 2011-01-25 13:14:32

+0

@salman A,不是真的,因为如果我把它作为一个jQuery对象返回,我可以立即用它做其他事情 – Koesper 2011-01-25 13:31:29

回答

2

我不知道是否能有所帮助,这里是一些代码:

$(document).ready(function() { 
     $('input:not(:checked)').each(function() { 
      if($('input[name='+$(this).attr('name')+']:checked').size() == 0) 
      { 
       $(this).addClass('highlight'); 
      } 
     }); 
    }); 

有了这个,你只强调没有任何无线电检查尚未团体的无线电选中。 它适合您的需求吗?

0

这个怎么样?

function is_answered(valueName) 
{ 
    var result=$('input[name='+valueName+']:checked').size(); 
    return result > 0; 
} 
+0

这会使它确实更容易:-)但不幸的是,添加更多元素到我的DOM是一点点超出我的项目范围。还是)感谢你的建议! – Koesper 2011-01-25 13:07:59

0

试试这个:

var $radios = $("input[type='radio']") 
//loop through all the radios that are checked 
$radios.filter(":checked") 
.each(function(){ 
    //filter out all radios with the current name, and add something to recognize them with 
    $($radios).filter("[name='" + $(this).attr("name") + "']").addClass("checked") 
}) 
.end() 
.filter(":not(.checked)").addClass("highlight"); 

根据用例,这可能是更好:

$("input[type='radio']").filter(":not(:checked)").addClass("highlight"); 

但我不知道,如果你需要的“检查”类别的东西太。

+0

嗨Excelian,你的第一个建议给出了我想要的结果,事实上,它有点更好,因为它只使用一个jQuery变量。我仍然想摆脱“检查”类,因为我不需要它。 – Koesper 2011-01-25 13:52:21