Kevin Kendzia
Kevin Kendzia

Reputation: 248

Disable onclick when event is from another onclick

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?

Upvotes: 0

Views: 137

Answers (3)

guest271314
guest271314

Reputation: 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>

Upvotes: 1

devlin carnate
devlin carnate

Reputation: 8592

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

Upvotes: 0

Chris
Chris

Reputation: 4810

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);
    });
});

Upvotes: 1

Related Questions