Jim Jim - 5 months ago 25
Javascript Question

Need either Mutually Exclusive Checkboxes or Deselectable Radio Buttons

I need either:


  • Radio buttons that can be deselected OR

  • Mutually exclusive checkboxes



Background info:

I have a repeater.

For each row in the repeater there is an associated document that can be either "Generated" or "Reprinted".

The user should be able to select up to one checkbox in any given row. After this, one button click will handle all of their selections in one pass.

When I search for "Mutually exclusive checkboxes", the common response is, "This is what radio buttons are for."

When I search for "Deselectable radio buttons", the common response is, "This is what check boxes are for."

Others have suggested custom JavaScript/ jQuery solutions but none in which the number of CheckBoxes/RadioButtons and their IDs are variable.

I find it hard to believe that this functionality isn't supported by ASP.NET controls. Has anyone faced this problem? Is there another control I could use or does this require a custom solution?

NOTE: The only third party software I have access to is Telerik's UI for ASP.NET AJAX, which doesn't contain an obvious solution.

Jim Jim
Answer

I'm more of a StackOverflow guy, but I eventually found this on GitHub.

https://gist.github.com/kikegarcia/6104607

And here's what I ended up with, along with some documentation. Basically the same thing, but using .prop instead of .attr since reading Tim Down's explanation of the difference between the two here: .prop() vs .attr()

// mutually exclusive checkboxes within the scope of a repeater row
function cbOnChange(sender) {   
  if (sender.checked)                                                      
    $(sender).siblings(":checkbox").prop("checked", false);
    //  1        2          3         4      5        6
}
  1. Get the event-initiating checkbox as a jQuery object.
  2. Get the sibling elements of our checkbox...

  3. ... with type = "checkbox".

  4. Access their properties...

  5. ... of type "checked"...
  6. ... and set them to false. => Automatic unchecking of sibling checkboxes.
Comments