我有这样的表格:
<form name="test">
<input type="radio" required="required" name="a" value="1">1
<input type="radio" required="required" name="a" value="X">X
<input type="radio" required="required" name="a" value="2">2
<br />
<input type="radio" required="required" name="b" value="1">1
<input type="radio" required="required" name="b" value="2">2
</form>
我想实现这个目标:
If a=1 then b=1
If a=X then unset b
If a=2 then b=2
我试过这个,但它没有做任何事情:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#test').on('change', function() {
if ($("input[name='a']:checked").val()=="1") {
$( "#b" ).prop( "checked", true );
}
});
});
</script>
这里缺少什么?
答案 0 :(得分:2)
在名为radio
的{{1}}按钮上绑定更改事件,获取其值,在名称为a
的{{1}}中找到相同的内容,并检查其属性,如下所示:
radio button
b
PS:如果您希望可以将
$('input[name="a"]').on('change', function() { var selected = $('input[name="a"]:checked').val(); if (selected == "X") { $('input[name="b"]:checked').prop("checked", false); return false; } $('input[name="b"][value="' + selected + '"]').prop("checked", true); });
属性添加到<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <form name="test"> <input type="radio" required="required" name="a" value="1">1 <input type="radio" required="required" name="a" value="X">X <input type="radio" required="required" name="a" value="2">2 <br /> <input type="radio" required="required" name="b" value="1">1 <input type="radio" required="required" name="b" value="2">2 </form>
设置名称disabled
,以便不允许用户更改
答案 1 :(得分:2)
您应该将<form name="test">
<input type="radio" required="required" name="a" value="1">1
<input type="radio" required="required" name="a" value="X">X
<input type="radio" required="required" name="a" value="2">2
<br />
<input type="radio" required="required" name="b" value="1">1
<input type="radio" required="required" name="b" value="2">2
</form>
事件绑定到radiobutton,而不是表单。
像这样:
<强> HTML 强>
$(document).ready(function() {
$("input[name='a']").on("change", function() {
$("input[name='b']").prop("checked", false);
$("input[name='b'][value='" + $(this).val() + "']").prop("checked", true);
});
});
<强>的Javascript 强>
{{1}}