Artoo Smith
Artoo Smith

Reputation: 425

jQuery always has one checkbox checked

With the following HTML checkbox code

<input type="checkbox" class="example" checked />2016
<input type="checkbox" class="example" />2015
<input type="checkbox" class="example" />2014
<input type="checkbox" class="example" />2013
<input type="checkbox" class="example" />2012
<input type="checkbox" class="example" />2011
<input type="checkbox" class="example" />2010

What changes do I need to make to the following jQuery

 $(function() { 
     $('input[type="checkbox"]').bind('click',function() {
        $('input[type="checkbox"]').not(this).prop("checked", false);
     });
});

so that one of the checkboxes is checked at all times not allowing blank checkboxes?

Upvotes: 0

Views: 2001

Answers (3)

Carsten Massmann
Carsten Massmann

Reputation: 28236

There is yet another (shorter) way of achieving the same:

$(function() { 
   $(':checkbox').click(function(){
      $(this).prop('checked', true).siblings(':checkbox').prop("checked", false);
   });
});

It will simply always keep the clicked element checked and all siblings unchecked.

Upvotes: 0

namhd
namhd

Reputation: 337

Seems like you didn't want to use radio button instead. This is updated code of yours, it works as desired. You will need to make sure that a checked box will not unchecked by re-clicking.

$(function() { 
     $('input[type="checkbox"]').bind('click',function() {
         if($(this).prop('checked') === false) {
           $(this).prop('checked', true);
         }
         $('input[type="checkbox"]').not(this).prop("checked", false);
     });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<input type="checkbox" class="example" checked />2016
<input type="checkbox" class="example" />2015
<input type="checkbox" class="example" />2014
<input type="checkbox" class="example" />2013
<input type="checkbox" class="example" />2012
<input type="checkbox" class="example" />2011
<input type="checkbox" class="example" />2010

Upvotes: 2

num8er
num8er

Reputation: 19372

Seems like You've beautiful UI components with checkboxes, so that's why You don't want to use radio inputs?

About Your question: Your code works as desired

 $(function() { 
     $('input[type="checkbox"]').bind('click',function() {
        $(this)
          .parent()
          .find('[type="checkbox"]').not(this)
          .removeAttr('checked');
     });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" class="example" checked />2016
<input type="checkbox" class="example" />2015
<input type="checkbox" class="example" />2014
<input type="checkbox" class="example" />2013
<input type="checkbox" class="example" />2012
<input type="checkbox" class="example" />2011
<input type="checkbox" class="example" />2010

Upvotes: 0

Related Questions