2011-01-25 36 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

相關問題