Reputation: 5119
HTML
<div>Group 1
<br>
<label>
<input type="checkbox" name="testing" value="B" checked="checked">A</label>
<br />
<label>
<input type="checkbox" name="testing" value="I">B</label>
<br />
<label>
<input type="checkbox" name="testing" value="A">C</label>
<br />
</div>
<div>Group 2
<br>
<label>
<input type="checkbox" name="testing2" value="B">A</label>
<br />
<label>
<input type="checkbox" name="testing2" value="I">B</label>
<br />
<label>
<input type="checkbox" name="testing2" value="A">C</label>
<br />
</div>
JS
$("input:checkbox").change(function () {
var checkname = $(this).attr("name");
if (this.checked) {
$("input:checkbox[name='" + checkname + "']").removeAttr("checked").parent().hide();
this.checked = true;
$(this).parent().show();
} else {
$("input:checkbox[name='" + checkname + "']").parent().show();
}
});
The hide/show script when a checkbox is checked works perfectly but if a checkbox is initialy check on window load, how to make it run the above script so it would hide the others not checked ?
http://jsfiddle.net/warface/uvYzW/
Upvotes: 1
Views: 2185
Reputation: 546
Add this code to the end:
$(function(){
$('input:checked').parent().siblings('label').hide();
$('input:checked').parent().show();
});
Upvotes: 0
Reputation: 437
You can use the following code to trigger the change event on the already checked checkboxes and cause your code to fire.
$("input:checkbox[checked]").trigger("change");
Updated fiddle: http://jsfiddle.net/uvYzW/2/
Upvotes: 4