我需要为一组单选按钮注册一个处理程序。我正在使用 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 语句中寻找的实际逻辑,但希望这将为您纠正当前代码提供基础。
关于jquery - 如何使用 JQuery 监听 RadioGroup 选定值的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4091554/