2009-08-26 183 views
2

我正在處理一個長表單,它有幾個單選按鈕組。jQuery選擇所有單選按鈕組

在底部有一個單選按鈕「不全」。當它被選中時,我想讓所有的「N」單選按鈕都被選中,但我無法使它工作。下面是代碼的簡化版本:

的jQuery:

$(document).ready(function(){ 
//initially hide the Remove All Questions 
$("div.#removeAllquest").hide(); 

//////////// Show Remove All Questions if radio button selected 
$("input.#RemoveAll").click(function() { 
    if ($(this).is(':checked')) 
    $("input:radio [class*='radioR']").attr("checked",true); 
    else 
$("input:radio [class*='radioR']").attr("checked",false); 
}); 

});

形式:

<table> 
    <tr> 
    <td>Y<input type="radio" name="row1" value="row1col1" class="q123col1"></td> 
    <td>N<input type="radio" name="row1" class="radioR" value="row1col2"></td> 
    <td>M<input type="radio" name="row1" value="row1col3" class="q123col3"></td> 
    </tr> 
    <tr> 
    <td>Y<input type="radio" name="row2" value="row2col1" class="q123col1"></td> 
    <td>N<input type="radio" name="row2" class="radioR" value="row2col2"></td> 
    <td>M<input type="radio" name="row2" value="row2col3" class="q123col3"></td> 
    </tr> 
    <tr> 
    <td>Y<input type="radio" name="row3" value="row3col1" class="q123col1"></td> 
    <td>N<input type="radio" name="row3" class="radioR" value="row3col2"></td> 
    <td>M<input type="radio" name="row3" value="row3col3" class="q123col3"></td> 
    </tr> 
    <tr> 
    <td colspan="2">No All </td> 
    <td> 
     <input name="RemoveAll" id="RemoveAll" type="radio" value="Y"> 
    </td> 
    </tr> 
</table> 

我在做什麼錯?

回答

11

這些都應該工作 - 第一個我試圖保持你的風格。隨着第二次,我改變了一下風格。在你的示例中,一旦他們被檢查,沒有真正的方法來取消選中他們。

$("input.#RemoveAll").click(function() { 
    if ($(this).is(':checked')) 
     $("input:radio.radioR").attr("checked", "checked"); 
    else 
     $("input:radio.radioR").removeAttr("checked"); 
}); 

$("#RemoveAll").click(function() { 
    if ($(this).is(':checked')) 
     $(".radioR").attr("checked", "checked"); 
    else 
     $(".radioR").removeAttr("checked"); 
}); 
+0

謝謝安迪!我用你的第一個選項,它像冠軍一樣工作。我想取消選中單選按鈕......但是花了我很長時間才弄到這麼遠,我覺得現在有點超過我的頭:) – Chnikki 2009-08-27 14:27:39

+0

我不認爲你真的必須刪除「checked」屬性因爲您無論如何都一次只能選擇一個單選按鈕,但其餘代碼看起來不錯。 – 2010-08-24 16:11:10

1

首先,據我所知,只檢查接受檢查爲XHTML中的有效值。因此,像下面應該做的伎倆

$("#RemoveAll").change(function() { 
    if ($(this).is(':checked')) 
      $("input:radio.radioR").attr("checked","checked"); 

    else 
      $("input:radio.radioR").removeAttr("checked"); 
    }); 
}); 

注意選擇爲刪除更改所有單選按鈕添加輸入元素過濾器是不是真的有必要爲$(「#ID」)調用的document.getElementById 。

1

這應該做你需要什麼...

$("input.#RemoveAll").click(function() { 

    if ($(this).attr('checked') === "checked"){ 

    $("input:radio[class*='radioR']").attr("checked","checked"); 

    }else{ 

    $("input:radio[class*='radioR']").removeAttr("checked"); 

    } 
}); 

希望它能幫助,思南。