简体   繁体   English

如果选中jquery,请取消选中复选框

[英]Uncheck checkbox if checked with jquery

I have 3 checkboxes in a row and this code I found works GREAT 我连续有3个复选框,我找到的代码很有用

$('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" 是的我明白单选按钮通常用于“只允许选择1个项目”,但即使是单选按钮也不能点击“取消选择”

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 复选框更自然,能够取消选择但是我的功能我尝试取消选择,如果已经选中并点击它总是转到else语句

$('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. 有3个复选框,目前我的功能只允许其中1个复选框。 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: 在该行的复选框上设置checked = false时,只需省略单击的复选框,这样它就会像常规复选框一样,例如:

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

Here's a fiddle 这是一个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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