There are two checkboxes. One is immediately marked, the second is not. It is necessary when you click on the checkbox, both changed the checked state to the opposite of what is now. If you click on only one checkbox, then everything is ok. But if after clicking on another - everything breaks down.

In any case, there must be at least one checkbox.

$('input:checkbox').click(function () { if( !$(this).is(':checked')) { $('input:checkbox').not(this).eq(0).attr('checked', 'checked'); $(this).eq(0).removeAttr('checked'); } else { $('input:checkbox').not(this).eq(0).removeAttr('checked'); $(this).eq(0).attr('checked', 'checked'); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="recruiter-switch" class="onoffswitch-checkbox" id="recruiter" checked> <input type="checkbox" name="company-switch" class="onoffswitch-checkbox" id="company"> 

  • In fact, now everything works as it should. - Cheg
  • Shout several times on the same checkbox. And then on another. In any case, there should be at least one checkbox checked - Ivan Kucher
  • And what do you radio button 's not pleased? They are just for this purpose and intended. - Cheg
  • @Cheg The idea is that I style them under an element like switch. Such a switch off / on. If you inspect checkboxes, then JS works in the html itself, the checked state changes, but the daw disappears somewhere after a few clicks. - Ivan Kucher

2 answers 2

You can do this:

 $('input:checkbox').click(function () { if( !$(this).is(':checked')) { $('input:checkbox').not(this).eq(0).prop('checked', true); } else { $('input:checkbox').not(this).eq(0).prop('checked', false); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="recruiter-switch" class="onoffswitch-checkbox" id="recruiter" checked> <input type="checkbox" name="company-switch" class="onoffswitch-checkbox" id="company"> 

It does not make sense to change the flag for the current one; it is automatically done.

  • Yes it works. Thank you) - Ivan Kucher

That's so short

 $('input:checkbox').click(function () { var a = !$(this).is(':checked'); $('input:checkbox').not(this).eq(0).prop('checked', a); })