使用.each函数时如何返回选定的radiogroup值?

时间:2013-03-07 07:18:25

标签: jquery oracle-apex

在下面的HTML中,我想只检索哪个radiogroup选项 为特定的无线电组选择。

以下是我希望这个工作的方式,我基本上会让用户在网页上输入所需的值,同时选择他们可用的radiogroup选项 - 是这种情况是/否,但我会然后在按下按钮时扫描页面,然后只显示他们选择了哪些放射性组件选项。

因此,基于以下HTML代码,如果对于名为“已婚”的无线电组,他们选择“是”,对于名为“儿童”的无线电组,他们选择“否”,那么我现在想要警告屏幕:

YES
NO

仅限

YES
YES
NO
NO

我正在使用.each函数扫描页面上的所有元素,并检查类型是否为“radio”,但不幸的是我得到了重复的响应,这是我不想要的。

如何扫描页面,每个放射组只返回YES和NO?

<fieldset class="radio_group" tabindex="-1" id="MARRIED_RG">
<table class="radiogroup" datatable="0" role="presentation" summary="">
<tbody><tr>
<td nowrap="nowrap">
<input type="radio" class="tooltip" value="YES" name="married" id="MARRIED_RG_0"><label for="MARRIED_RG_0">Yes</label></td><td nowrap="nowrap">
<input type="radio" class="tooltip" value="NO" name="married" id="MARRIED_RG_1"><label for="MARRIED_RG_1">No</label></td></tr></tbody></table>
</fieldset>


<fieldset class="radio_group" tabindex="-1" id="CHILDREN_RG">
<table class="radiogroup" datatable="0" role="presentation" summary="">
<tbody><tr>
<td nowrap="nowrap">
<input type="radio" class="tooltip" value="YES" name="children" id="CHILDREN_RG_0"><label for="CHILDREN_RG_0">Yes</label></td><td nowrap="nowrap">
<input type="radio" class="tooltip" value="NO" name="children" id="CHILDREN_RG_1"><label for="CHILDREN_RG_1">No</label></td></tr></tbody></table>
</fieldset>

基于以上所述,我基本上需要一种不重复无线电组结果的方法 - 需要不同的值。

我的代码如下:

$(':radio').each(function() { // loop through each radio button
        nam = $(this).attr('name'); // get the name of its set
        if ($(':radio[name="'+nam+'"]:checked').length > 0) { 
        // see if any button in the set is checked
            alert(nam);
        }
    });

因此,基于使用上述HTML的代码,我得到了正确的值,但因为我使用的是.each函数,它返回了无线电组的每一行,即:

MARRIED_RG_0    YES
MARRIED_RG_1    YES
CHILDREN_RG_0   NO
CHILDREN_RG_1   NO

我只想回来:

MARRIED_RG_0    YES
CHILDREN_RG_1   NO

2 个答案:

答案 0 :(得分:1)

如果你可以使用与.each()不同的东西,你可以试试这样的东西:

$("input:radio[name='married']:checked").val()
$("input:radio[name='children']:checked").val()

问题澄清后编辑: 请尝试使用$(this).is(":checked")代替$(':radio[name="'+nam+'"]:checked').length > 0

$('input:radio').each(function() { // loop through each radio button
    nam = $(this).attr('name'); // get the name of its set
    if ($(this).is(":checked")) { 
        alert(nam + ": " + $(this).val());
    }
});

答案 1 :(得分:1)

可能有一种更聪明的方法,但您可以先收集单选按钮组列表,然后遍历该列表而不是每个单选按钮。

var sets = [];

// first get all unique sets
$(':radio').each(function () {
    var name = $(this).attr('name');
    if ($.inArray(name, sets) === -1) {
        sets.push(name);
    }
});

// then loop through the sets
$.each(sets, function (index, set) {
    if ($(':radio[name="' + set + '"]:checked').length > 0) {
        // see if any button in the set is checked
        alert(set);
    }
});

演示:http://jsfiddle.net/SF4qj/

相关问题