如何使用JQuery监听RadioGroup的选定值的变化?

21

我需要为一组单选按钮注册一个处理程序。 我正在使用JQuery,并希望它的.change方法可以实现此操作。 然而,我没有得到期望的行为。

这里是我编写的示例代码片段。 遗憾的是,“radioValueChanged”仅在初始加载时被调用。 选择true / false都不会触发处理程序。

<html>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>

<form id="myForm">
    <div id="Question1Wrapper">
        <div>
            <input type="radio" name="controlQuestion" id="valueFalse" value="0" />
            <label for="valueFalse">
                False</label>
        </div>
        <div>
            <input type="radio" name="controlQuestion" id="valueTrue" value="1" />
            <label for="valueTrue">
                True</label>
        </div>
    </div>
    <div id="Question2Wrapper">
        <div>
            <label for="optionalTextBox">
                This is only visible when the above is true</label>
            <input type="text" name="optionalTextBox" id="optionalTextBox" value="" />
        </div>
    </div>

    <script type="text/javascript">
        jQuery(document).ready(function ()
        {
            $("#controlQuestion").change(radioValueChanged('controlQuestion'));
        })

        function radioValueChanged(radioName)
        {
            radioValue = $('input[name=' + radioName + ']:checked', '#myForm').val();

            alert(radioValue);

            if(radioValue == 'undefined' || radioValue == "0")
            {
                $('#Question2Wrapper:visible').hide();
            }
            else
            {
                $('#Question2Wrapper:visible').show();
            }
        } 
    </script>
</form>

2个回答

34

这里有几个问题。

  1. 你会立即运行 radioValueChanged('controlQuestion'),因为那是一个方法调用而不是函数分配。

  2. 选择器 $("#controlQuestion") 是错误的,你没有任何具有id为controlQuestion的元素。

  3. radioValueChanged 方法没有正确地处理值,就像它们被传递给jQuery事件处理程序一样。

你可以尝试以下内容:

jQuery(document).ready(function ()
    {
        $("input[name='controlQuestion']").change(radioValueChanged);
    })

    function radioValueChanged()
    {
        radioValue = $(this).val();

        alert(radioValue);

        if($(this).is(":checked") && radioValue == "0")
        {
            $('#Question2Wrapper').hide();
        }
        else
        {
            $('#Question2Wrapper').show();
        }
    } 

说实话,我不确定这是否是您在 if 语句中要查找的实际逻辑,但希望这将为您提供纠正当前代码的基础。


太棒了,谢谢。你可以看出JavaScript / jQuery相对较新/生疏。所以'#'前缀始终是ID而不是名称...很好知道:) "$(this).is(":checked")"具体是做什么的?我想要它的相反操作。也就是说,如果没有选择任何值,我希望问题被隐藏。 - Justin
1
@Justin 是的,选择器实际上遵循CSS选择器规则,你可以在w3上搜索CSS选择器...层次结构、名称、ID等。此外,is是一个jQuery函数:http://docs.jquery.com/Is(尽管我没有在api.jquery.com上找到它,这让我有些担心)。 - Quintin Robinson
is() 函数 绝对 在 api 子域名下: api.jquery.com/is/ - David Thomas
@David Thomas 谢谢,我实际上并没有尝试将“is”添加到api网址并浏览,尽管我曾考虑过。顺便说一句,你让我饿了,想吃饭碗! - Quintin Robinson

0
$('#Question2Wrapper:visible').show();

去掉:visible,这样只有在div已经显示的情况下才会选择它,实际上如果它被隐藏了就永远不会显示。
$('#Question2Wrapper').show();

言归正传,我认为Quintin提到了大部分要点。这里有几个问题需要解决。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接