2011-07-29 76 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