2013-03-11 34 views
2

我有一組單選按鈕,我想將選中的attr添加到其中的一個。 這是我的代碼:如何使用jQuery將選中的attr添加到單選按鈕nth-child?

<input type="radio" name="radioButton" id="rd1"> 
<input type="radio" name="radioButton" id="rd2"> 
<input type="radio" name="radioButton" id="rd3"> 
<input type="radio" name="radioButton" id="rd4"> 
<input type="radio" name="radioButton" id="rd5"> 

<script> 
    $('input[name=slider]:nth-child(3)').prop('checked', true); 
</script> 

和我測試的腳本.attr( '檢查', '檢查')。 但腳本不能正常工作。我的錯是什麼?

+1

試$( '輸入[名稱=單選]:第n個孩子(3)')ATTR( 「選中」, 「選中」) – Przemek 2013-03-11 08:10:02

+0

你的名字從滑蓋改爲單選按鈕,對於這一點。工作 – Przemek 2013-03-11 08:16:09

回答

2
$('input[name=radioButton]:nth-child(3)').attr('checked', true); 

$('input[name=radioButton]:nth-child(3)').attr('checked', 'checked'); 

這裏是jsFiddle

+0

,如果他們在同一空間共存不能與多個按鈕組的工作:[的jsfiddle/76pyq2ae(http://jsfiddle.net/MrPolywhirl/76pyq2ae/)。如果你將它們分組到一個列表中,這將起作用:[jsfiddle/Lrb46qL3](http://jsfiddle.net/MrPolywhirl/Lrb46qL3/)。 – 2015-02-21 22:57:14

2

嘗試:

$('input[name=radioButton]:eq(2)').prop('checked', true); 
+0

感謝的作品 – bobsilon 2013-03-11 08:11:37

0

試試這個:

<script> 
    $('input[name=radioButton]:nth-child(3)').attr('checked', 'checked'); 
</script> 
0

試試看看這個代碼。 使用attr而不是prop。

$('input[name=slider]:nth-child(3)').attr('checked', true); 
相關問題