从以元素名称为目标的元素中获取值

Get the value from an element targeted by its name

本文关键字:元素 获取 目标      更新时间:2023-09-26

让我试着解释一下我的问题。我有一个单选按钮"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());
});

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

非常感谢您的帮助

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

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

它们听起来很奇怪,但很难修改。不管怎样,这不是问题的根源。

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

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

工作演示