0

I have 2 checkboxes. They shall be synced, so i did some jQuery

<input type="checkbox" id="check1" onclick="jQuery('#check2').trigger('click')">
<input type="checkbox" id="check2" onclick="jQuery('#check1').trigger('click')">

When I press check1, check2 will be checked/unchecked, but also triggers the onclick of check2, so check1 will be checked -> unchecked. How can I solv this?

Kevin Kendzia
  • 248
  • 1
  • 12

3 Answers3

1

In general, you should use a radio button for this, as it has the desired functionality built in. To answer your question however, you need to set/remove the checked state of the box, instead of triggering the click.

<input type="checkbox" id="check1" onclick="jQuery('#check2').attr('checked', false)">
<input type="checkbox" id="check2" onclick="jQuery('#check1').attr('checked', false)">

If you want to sync them, then you could move the JS so that it is not inline and use something like:

jQuery(function() {
    var boxes = $('input[type=checkbox]');

    boxes.on('click', function(evt) {
        var other = boxes.not( $(this) );

        if( other.is(':checked') )
            other.removeAttr('checked');
        else
            other.attr('checked', true);
    });
});
Chris
  • 4,762
  • 3
  • 44
  • 79
1

Try placing elements inside parent container , using change event attached to parentElement :checkbox ; within change handler set siblings elements checked property to current element checked property

$("div :checkbox").on("sync", function(e) {
  console.log(e.target.id)
})

$("div :checkbox").on("change", function() {
  $(this).siblings().prop("checked", this.checked)
  .trigger("sync")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>
  <input type="checkbox" id="check1" />
  <input type="checkbox" id="check2" />
</div>
guest271314
  • 1
  • 15
  • 104
  • 177
0

The onclick event you're using in your html elements is unnecessary and confusing. Instead, I would suggest you add a class to both elements, and then you can uncheck all elements other than the one that was just clicked on.

HTML

<input type="checkbox" id="check1" class="myClass" >Box 1
<input type="checkbox" id="check2" class="myClass">Box 2

JQuery / Javascript

var $checkboxes = $('.myClass');
$checkboxes.click(function() {
   $checkboxes.not(this).prop('checked', false);
});

JS Fiddle demo

devlin carnate
  • 8,309
  • 7
  • 48
  • 82