2011-07-29 74 views
0

我有一個<div>與選項框:如何獲取所選單選按鈕的值?

<div id='RB-01'> 
<span>Item_1</span><input type='radio' name='RB01' value='1'><br /> 
<span>Item_2</span><input type='radio' name='RB01' value='2'><br /> 
<span>Item_3</span><input type='radio' name='RB01' value='3'><br /> 
</div> 

然後用jQuery我想要得到數量上的帳戶進行查了radiobox:

var obj; 
var tempId = "RB-01"; 
if ($('div[id=' + tempId + ']')) { 
    $('div[id=' + tempId + '] input').each(function() { 

    ...here I need save in the variable obj the number on an account input that was checked... 

    }); 
} 
+1

@PabloFernandez:你的代碼將無法通過JSLint的,你需要使用''=== – qwertymk

+0

@qwertymk如此真實。但正如Brendan Eich自己所說:「jslint可以吸引它」 –

回答

0

聽起來像是你需要

$('div[id=' + tempId + '] input:checked').each(function() { 

    var number = $(this).val(); 

    }); 

你可能很容易發現這個jQuery開發API網站...

JQuery each

+0

其實他想要檢查的廣播輸入。所以這是行不通的。 – kasdega

+0

我編輯了我的答案 - 看起來就像我編輯你的評論! –

2
var obj = null; 
var tempId = "RB-01"; 

if ($('div[id=' + tempId + ']')) { 
    obj = $('#' + tempId + ' input:checked').val(); 
} 

有沒有必要使用div[id=RB-01]因爲ID是唯一的選擇器。只需使用#RB-01。然後使用:checked選擇器獲取選中的單選按鈕。

+0

我更喜歡這個版本! –

+0

是的沒有必要的循環只抓取選中的收音機。 – kasdega

+0

'$('div [id ='+ tempId +']')'永遠是真的! :) – Shef

1
var obj = null, 
    tempId = "RB-01", 
    $div = $('#'+tempId); 

if ($div.length){ 
    obj = $div.find('input:radio:checked').val(); 
} 

Here is a demo