jQuery .prop('checked', true) don't work

27,939

Solution 1

If you want to allow multiple checks, but disallow zero checks, this code should suffice:

$('input[type=checkbox]').on('click', function(event) {
  if(!$('input[type=checkbox]:checked').length) {
    $(this).prop('checked', true);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" checked="checked"/>
    <input type="checkbox"/>
        <input type="checkbox"/>

Solution 2

event.preventDefault() makes your .prop not working

You'll also need to uncheck others when a checkbox is checked.

$('input[type=checkbox]').on('click', function(event) {
  // Remove this line
  // event.preventDefault();
  
  if ($('input[type=checkbox]:checked').length === 1) {
    if ($(this).is(':checked')) {
      return false; // this is checked
    }
    return false; // and this is the only one check	
  } else {
    
    // Uncheck others
    $('input[type=checkbox]').prop('checked', false);
    
    $(this).prop('checked', true);
    alert($(this).prop('checked')); // this return true
  }


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" checked="checked" />
<input type="checkbox" />
<input type="checkbox" />

Share:
27,939
aahhaa
Author by

aahhaa

Updated on July 05, 2022

Comments

  • aahhaa
    aahhaa almost 2 years

    I have a set of simple checkboxes, that can check multiple option, but I wish it to behave like a radio button where there will always be one option that is checked.

    as you can see in my code, the checkbox will checked, and than uncheck. please let me know what I did wrong. Thanks

    $('input[type=checkbox]').on('click', function(event) {
    		event.preventDefault();
    		if($('input[type=checkbox]:checked').length === 1 && $(this).is(':checked')) {
    				return false; 
                    // there is only one checked AND the checked one is $this and we want to prevent it from uncheck
    		} else {
    			$(this).prop('checked', true);
    			alert($(this).prop('checked')); // this return true
    		} 
    
    	});
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <input type="checkbox" checked="checked"/>
        <input type="checkbox"/>
            <input type="checkbox"/>