2
votes

I have 3 checkboxes in a row and this code I found works GREAT

$('input:checkbox').click(function () {
    $(this).closest('tr').find('input:checkbox').prop('checked', false);
    $(this).prop('checked', true);
});

However, I have a business requirement in which I'm told if someone clicks on a checkbox that is already checked, that it must uncheck. Yes I understand that radio buttons typically are used in the "only allow 1 item to be selected" however even a radio button is not something you can click to "de-select"

Checkboxes are more natural to be able to un-select but with my function I was trying unselect if already selected and clicked and it always goes to the else statement

$('input:checkbox').click(function () {
    //alert('c');
  $(this).closest('tr').find('input:checkbox').prop('checked', false);

  if ($(this).checked)
  {
      alert('f');
      $(this).prop('checked', false);
  }
  else {
      alert('t');
      $(this).prop('checked', true);
  }

});

Summary

There are 3 checkboxes , currently my function only allows 1 of them to be checked. However now I need to be able to click on the currently checked checkbox and uncheck it

enter image description here

1
What do you want? Explain in parts and better way. - divy3993
There are 3 checkboxes , currently my function only allows 1 of them to be checked. However now I need to be able to click on the currently checked checkbox and uncheck it - user5154099
with $(this).closest('tr').find('input:checkbox').prop('checked', false); you uncheck the clicked checkbox, that's why it always goes to else statement - Kristijan Iliev
So why is it that you can't just use radio buttons? If you only want 1 checkbox to be selected per row that's exactly what a radio button would do. - Rafa
Yes, I understand that, so I do want to use that code but wrap a conditional around it checking it the checkbox is checked already and being clicked on because I do need to allow for unselecting of all of them - user5154099

1 Answers

3
votes

Just omit the clicked checkbox when setting checked = false on checkboxes in that row, so that it will behave like a regular checkbox, eg:

$(this).closest('tr').find('input:checkbox').not(this).prop('checked', false);

Here's a fiddle