从名称所针对的元素中获取值

时间:2014-09-24 10:04:51

标签: javascript jquery

让我试着解释一下我的问题。我有一个单选按钮“jform [display]”,它允许显示隐藏的div“greenRect”。 使用以下代码,它不起作用。

$("input[name='jform[display]']").on('click', function() {
    if ($("input[name='jform[display]']").val() == 1) {
        greenRect.show();
        alert("Value of the Radio Button="+$("input[name='jform[display]']").val());
        return;
    }
    greenRect.hide();

    //It does not work (always=1)!!!
    alert("Value of the Radio Button="+$("input[name='jform[display]']").val());
});

元素$(“input [name ='jform [display]']”)。val()总是== 1

如果我修改$(“input [name ='jform [display]']”)。val()到$(this).val(),它可以工作!

$("input[name='jform[display]']").on('click', function() {
    if ($(this).val() == 1) {
        greenRect.show();
        alert("Value of the Radio Button="+$(this).val());
        return;
    }
    greenRect.hide();

    alert("Value of the Radio Button="+$(this).val());
});

为什么它适用于option2而不适用于option1。我以为两者都很相似。 以下是JSFIDDLE的代码:http://jsfiddle.net/4zmqzecs/2/

非常感谢您的帮助

PS: 我的元素的名称由API生成:

name=jform[display]
id=jform_test0
id=jform_test1

听起来很奇怪,但很难修改。无论如何,这不是问题的根源。

1 个答案:

答案 0 :(得分:1)

您应该使用:checked选择器获取已选中单选按钮的值:

$("input[name='jform[display]']:checked").val()

<强> Working Demo

相关问题