jquery - 如何使用 JQuery 监听 RadioGroup 选定值的更改?

标签 jquery radio-button onchange radio-group

我需要为一组单选按钮注册一个处理程序。我正在使用 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>

最佳答案

这里有一些问题。

  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 语句中寻找的实际逻辑,但希望这将为您纠正当前代码提供基础。

关于jquery - 如何使用 JQuery 监听 RadioGroup 选定值的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4091554/

相关文章:

javascript - 悬停时删除我的图像

jquery - 在 jQuery 中使用 .load() 将文本插入文本区域

javascript - 将最后一个表行的选定值复制到新行

javascript - 尝试验证我的单选按钮,但它不起作用

ruby - cucumber 测试 - 选择哪种语法来测试单选按钮选择?

css - 单选按钮标签样式

php - 下拉 onchange 调用 PHP 函数

javascript - 具有所需 CSS 的 Jquery 插件

javascript - 获取所选下拉列表项的值

Javascript 选择下拉菜单 onchange 未正确触发