Beep Beep - 1 month ago 7
HTML Question

check box if select one un-select all other

Ok, so i have a list of check boxes 1, 2, 3, 4 and 5. I would like the function to select 2, 3, 4 and 5 but if 1 is selected then un-select 2, 3, 4 and 5, once 2 to 5 are un-selected display a message in a div.

So far I can select 1 and one of the others... and the message comes on selection of 1

problem 1
I cant un-select 2 to 5 once 1 is selected

problem 2
The message is displayed on page load even if the box is un-selected.

HTML

<input type="checkbox" class="" value="checkbox" name="CheckboxGroup1" id="boxchecked" />
one <br/>

<input type="checkbox" class="check" />
two <br/>

<input type="checkbox" class="check" />
three <br/>

<input type="checkbox" class="check" />
four <br/>

<input type="checkbox" class="check" />
five

<div id="hidden">Two to five can not be selected whilst you have one selected</div>


JavaScript

$('input.check').on('change', function() {
$('input.check').not(this).prop('checked', false);
});

$(document).ready(function(){
$("#boxchecked").click(function ()
{
if ($("#boxchecked").is(':checked'))
{
$("#hidden").show();
}
else
{
$("#hidden").hide();
}
});
});

$('input[name=CheckboxGroup1]').attr('checked', false);

Answer

Here is what I propose. How about giving the checkbox that can only be singly checked a class, and the others another class?
Hope it helps.

$('input[type="checkbox"]').on('click', function() {
    if($(this).hasClass('singlecheck')) {
       if($('input.multicheck').is(":checked")) {
         $('#warning').show();  
       }
       $('input.multicheck').prop('checked', false);
    } else {
      $('input.singlecheck').prop('checked', false);
      $('#warning').hide();
    }
     
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="singlecheck" value="one" name="CheckboxGroup1" id="boxchecked"  />
one <br/>

<input type="checkbox" class="multicheck" value="two"/>
two <br/>

<input type="checkbox" class="multicheck" value="three"/>
three <br/>

<input type="checkbox" class="multicheck" value="four"/>
four <br/>

<input type="checkbox" class="multicheck" value="five"/>
five

<div id="warning" style="display:none">Two to five can not be selected whilst you have one selected</div>

Comments