Skip to content
Advertisement

How to implement a click event on mutually exclusive checkboxes in jQuery?

I have two checkboxes:

<input id="outside" type="checkbox" value="1" data-gid="41820122" />
<input id="inside" type="checkbox" value="1" data-gid="41820122" />

I’ve made them mutually exclusive with:

$(function(){
  //mutually exclusive checkboxes
  $("input[data-gid]").click(function(){
    var gid = $(this).attr('data-gid');
    var fid = $(this).attr('id');
    var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
    checkboxes.attr("checked", false);
   });
});

This works fine. But I also want to add additional click functionality to the ‘inside’ checkbox. I want it to enable/disable a textarea on the same form, so I’ve done this:

$('#application_inside').click(function() {
        if ($(this).is(':checked')) {
          return $('textarea').removeAttr('disabled');
        } else {
          return $('textarea').attr('disabled', 'disabled');
        }
 });

So, if the ‘inside’ checkbox is checked, the textarea will be enabled, if it’s not checked, the textarea should be disabled.

The problem is that if the ‘inside’ checkbox is checked, and the user then checks the ‘outside’ checkbox, the ‘inside’ becomes unchecked (as it should be), but the textarea remains enabled. This appears to be because the ‘inside’ checkbox was never actually clicked by the user.

I’ve tried working around this with the following:

$(function(){
  //mutually exclusive checkboxes
  $("input[data-gid]").click(function(){
    var gid = $(this).attr('data-gid');
    var fid = $(this).attr('id');
    var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
    checkboxes.attr("checked", false);
    checkboxes.triggerHandler("click"); //new code to fire any click code associated with unchecked boxes
   });
});

But this just throws the browser in a loop, since the two different click events end up calling each other.

How can I keep my mutually exclusive code while still allowing the enable/disable code for the ‘inside’ checkbox to work?

Advertisement

Answer

You can create a custom event that you trigger when you click on #application_inside. Also you will fire this custom event when you uncheck other boxes because of the exclusiveness.

Here is an example: http://jsfiddle.net/gs78t/2/

Advertisement