简体   繁体   中英

Uncheck checkbox if checked with jquery

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

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM