代码之家  ›  专栏  ›  技术社区  ›  Justin

如何使用JQuery侦听对放射组的选定值所做的更改?

  •  21
  • Justin  · 技术社区  · 15 年前

    .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 回复  |  直到 13 年前
        1
  •  33
  •   Quintin Robinson    15 年前

    这里有一些问题。

    1. 你马上就跑 radioValueChanged('controlQuestion') 在脚本执行时,因为这是方法调用,而不是函数赋值。

    2. 选择器 $("#controlQuestion") 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语句中寻找的实际逻辑,但希望这将为您更正当前代码提供基础。

        2
  •  0
  •   John Strickler    15 年前
    $('#Question2Wrapper:visible').show();
    

    取出 :可见

    $('#Question2Wrapper').show();
    

    我有点离题,我认为昆廷的大部分观点都是正确的。这里有一些问题。