Reputation: 430
Can't get my head around this, trying to not only disable the rest of the checkboxes after two are selected, but also to turn the border around the "checkbox_group" from black to red
The javascript is:
$(document).ready(function() {
$(".cbox").on("click", function(){
var numberOfChecked = $('input.cbox:checkbox:checked').length;
if (numberOfChecked === 3){
$(this).prop('checked', false);
$("#checkbox_group").css({"border-color":"red"});
} else {
$("#checkbox_group").css({"border-color":"black"});
}
//console.log(numberOfChecked); // debugging
});
});
The styling for the div in question is:
#checkbox_group{
border: solid black 1px;
}
HTML:
<div id="checkbox_group">
<label>Sports</label>
<input type="checkbox" class="cbox" name="Sports" value="Sports" ><br>
<label>News</label>
<input type="checkbox" class="cbox" name="News" value="News" ><br>
<label>Entertainment</label
><input type="checkbox" class="cbox" name="Entertainment" value="Entertainment" ><br>
<label>Music</label>
<input type="checkbox" class="cbox" name="Music" value="Music" >
</div>
Upvotes: 0
Views: 787
Reputation: 3029
You just need to change the if statement to equal 2
instead of 3
. Then you need to check through the checkboxs and find which ones aren't checked already.
$(document).ready(function() {
$(".cbox").on("click", function(){
var numberOfChecked = $('input.cbox:checkbox:checked').length;
if (numberOfChecked === 2){
$(this).prop('checked', true);
$(".cbox").each(function(){
if ($(this).prop('checked') != true){
$(this).attr("disabled", true);
}
});
$("#checkbox_group").css({"border-color":"red"});
} else {
$("#checkbox_group").css({"border-color":"black"});
$(".cbox").each(function(){
if ($(this).attr('disabled') == "disabled"){
$(this).attr("disabled", false);
}
});
}
});
});
#checkbox_group{
border: solid black 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="checkbox_group">
<label>Sports</label>
<input type="checkbox" class="cbox" name="Sports" value="Sports" ><br>
<label>News</label>
<input type="checkbox" class="cbox" name="News" value="News" ><br>
<label>Entertainment</label
><input type="checkbox" class="cbox" name="Entertainment" value="Entertainment" ><br>
<label>Music</label>
<input type="checkbox" class="cbox" name="Music" value="Music" >
</div>
Upvotes: 2