Jus*_*tin 21 jquery onchange radio-group radio-button
我需要为一组单选按钮注册一个处理程序.我正在使用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>
Run Code Online (Sandbox Code Playgroud)
Qui*_*son 33
这里有一些问题.
您正在运行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();
}
}
Run Code Online (Sandbox Code Playgroud)
老实说,我不确定这是否是您使用if语句寻找的实际逻辑,但希望这将为您提供纠正当前代码的基础.