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

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

解决方法

这里有几个问题。

>您在脚本执行时立即运行radiovalueChanged(‘controlQuestion’),因为这是方法调用而不是函数分配。
>选择器$(“#controlQuestion”)是错误的,你没有任何id为controlQuestion的元素。
> 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语句寻找的实际逻辑,但希望这将为您更正当前的代码提供依据。

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...