我有一个代码,我希望我的复选框被选中和禁用。单击“零”时,应突出显示所有复选框,禁用除第0个复选框以外的所有复选框。类似地,一个,两个和三个单选按钮。这似乎并不一致。我在Chrome浏览器版本48.0.2564.116上尝试它。此外,Firefox上的行为很糟糕。有人可以让我知道我做错了吗?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input[name=radio_group]").prop("checked", false);
$("input[type=radio]").click( function( e ){
var whats_selected = $("input[name=radio_group]:checked").val()
$("input[type=checkbox]").attr('checked',false );
//disable all other checkboxes
for(i=0; i < 4; i++ ){
var elem = $("input[type=checkbox][name*=checkbox"+i+"]");
elem.click();
if( i != whats_selected ){
elem.prop("disabled", true);
}else{
elem.removeAttr("disabled");
}
}
});
});
</script>
</head>
<body>
<h1>Checkbox play</h1>
<h3>My 4 Radio Buttons</h3>
<input type="radio" name='radio_group' value=0>Zero<br>
<input type="radio" name='radio_group' value=1>One<br>
<input type="radio" name='radio_group' value=2>Two<br>
<input type="radio" name='radio_group' value=3>Three<br>
<p>And here are my checkboxes</p>
<input type='checkbox' id="chkbox0" name="checkbox0" value="checkbox0">Checkbox Zero<br>
<input type='checkbox' id="chkbox1" name="checkbox1" value="checkbox1">Checkbox One<br>
<input type='checkbox' id="chkbox2" name="checkbox2" value="checkbox2">Checkbox Two<br>
<input type='checkbox' id="chkbox3" name="checkbox3" value="checkbox3">Checkbox Three<br>
</body>
</html>
答案 0 :(得分:2)
我认为这应该可以解决问题(如果我的问题正确的话)
$("input[type=radio]").click(function(e) {
var whats_selected = $(this).val();
// check an disable all checboxes
$("input[type=checkbox]")
.attr('checked', true)
.prop('disabled', true);
// enable the targetted checkbox
$('#chkbox' + whats_selected)
.prop('disabled', false);
});
答案 1 :(得分:1)
这是另一种方法,匹配收音机/复选框对的索引:
var ndx;
$(document).ready(function() {
$("input[type=radio]").click(function() {
ndx = $("input[type=radio]").index(this);
$("input[type=checkbox]").attr('checked', true).prop('disabled', true);
$("input[type=checkbox]").eq(ndx).prop('disabled',false);
});
}); //END document.ready
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>My 4 Radio Buttons</h3>
<input type="radio" name='radio_group' value=0>Zero
<br>
<input type="radio" name='radio_group' value=1>One
<br>
<input type="radio" name='radio_group' value=2>Two
<br>
<input type="radio" name='radio_group' value=3>Three
<br>
<p>And here are my checkboxes</p>
<input type='checkbox' id="chkbox0" name="checkbox0" value="checkbox0">Checkbox Zero
<br>
<input type='checkbox' id="chkbox1" name="checkbox1" value="checkbox1">Checkbox One
<br>
<input type='checkbox' id="chkbox2" name="checkbox2" value="checkbox2">Checkbox Two
<br>
<input type='checkbox' id="chkbox3" name="checkbox3" value="checkbox3">Checkbox Three
<br>
&#13;