Question

I have several checkboxes. If a user checks any of them, I have to see if they are allowed to do that, if not, notify them and uncheck it. However, this get me in a loop as it triggers the change again! How can I over come this?

$('#step_1, #step_2, #step_3, #step_4').change(function(event) {
        if(!$('#section_2_active').attr('checked')){
            alert('You can not select output options when "Create Output" has not been selected.');

            $(this).attr('checked', false);

            $('#other_stages :checkbox:not(#section_2_active, #co_t)').change();
        }

});

I can not unbind and then rebind the change event as there is another plugin that is reliant on this event.

What other options do I have? I can attach a function call to each checkbox but I am hoping for something a bit more elegant, if not, I will default to this.

Thanks all for any help

Was it helpful?

Solution

You can use .trigger() to pass an additional parameter to your handler, we'll use loop. If it's false, don't run the other-element trigger again, like this:

$('#step_1, #step_2, #step_3, #step_4').change(function(event, loop) {
  if(!$('#section_2_active').attr('checked')){
    alert('You can not select output options when "Create Output" has not been selected.');
    $(this).attr('checked', false);
    if(loop !== false) 
      $('#other_stages :checkbox:not(#section_2_active, #co_t)').trigger('change', false);
  }
});

OTHER TIPS

The simplest change is something like this:

var inClickHandler = false;

function OnChecked(evt) { 
  if (inClickHandler) {
    inClickHandler = false;
    return;
  }
  inClickHandler = true;

  // Do your stuff.
}

Why do you call this line? $('#other_stages :checkbox:not(#section_2_active, #co_t)').change(); As far as I can see you don't need this and it won't then loop. The checkbox will still check unless you use event.preventDefault(); and the .attr('checked',false); won't trigger change, probably because of the issues you're having.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top