1

In my application, the user can check or uncheck a checkbox. On the change event:

    $('#Inactive_cb').change(function () {

    ....
    this.checked = !this.checked;

I check to see if the value has changed. In change(), I also check to see if they have permission to even do the change. If they don't I like to undo, the check/uncheck.

Question:

Is the way I have it above ideal? I have:

     this.checked = !this.checked;
Nate Pet
  • 44,246
  • 124
  • 269
  • 414
  • 1
    Maybe duplicate of http://stackoverflow.com/questions/1164213/how-to-stop-event-bubbling-on-checkbox-click – GTSouza Jul 12 '12 at 21:29
  • @GTSouza not a duplicate, that question deals with events triggering on parent elements when interacting with children. – sachleen Jul 12 '12 at 22:08

2 Answers2

1

You can use

if($(this).is(':checked')){
    $(this).attr('checked', false);
}

Or if you have a newer version of jQuery you can use

if($(this).is(':checked')){
    $(this).prop('checked', false);
}
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
GTSouza
  • 365
  • 4
  • 16
0

You can do it that way, it's simple and it works... but I would suggest just disabling the checkbox if the user does not have permissions to check it.

<input type="checkbox" id="foo" disabled />

jQuery code to set the disabled attribute

$("#foo").attr('disabled', 'disabled');

You'd do this when the form loads so users that don't have permissions don't even have the ability to check it. Obviously, you'd want to make this check again on the server side to make sure nobody removed the attribute from the element in the DOM and checked it when they weren't supposed to.

Might as well add... if you need to remove the attribute using JS, use jQuery's .removeAttr()

sachleen
  • 30,730
  • 8
  • 78
  • 73