首页 > 解决方案 > 如何使用 jQuery 或 JavaScript 选择和取消选择复选框

问题描述

我花了一个多小时为我的查询找到令人满意的答案或解决方案,但找不到。虽然我从这里遇到了一些帖子,但它们部分解决了我的问题。

我的问题:我有一个表单,其中包含由单选框选择分隔的三个不同部分的一组复选框。在这里,我想实现两件事:

  1. 当用户想要选择一个部分时,他/她单击单选按钮,应显示相应的部分,其中包含 DIV 内的复选框。

  2. 现在,当用户再次单击另一个单选按钮时,我希望上一节中的复选框应该被取消选中,反之亦然。

<input type="radio" value="fruit" id="fruit" checked="checked" />Favorite fruit?<br/>
<input type="radio" id="color" value="color" />Favorite color?<br/>
<input type="radio" id="sport" value="sport" />Favorite sport?<br/>

<div id="fruit">
  <input type="checkbox" value="apple"> Apple<br/>
  <input type="checkbox" value="apple"> Banana<br/>
  <input type="checkbox" value="apple"> Mango<br/>
</div>

<div id="color">
  <input type="checkbox" value="black"> Black<br/>
  <input type="checkbox" value="orange"> Orange<br/>
  <input type="checkbox" value="blue"> Blue<br/>
</div>

<div id="sport">
  <input type="checkbox" value="boxing"> Boxing<br/>
  <input type="checkbox" value="cricket"> Cricketbr/>
  <input type="checkbox" value="football"> Football<br/>
</div>

我需要编写 JavaScript 或 jQuery 代码。

标签: javascriptjqueryhtmlcheckbox

解决方案


有很多你想知道的例子。您只需要调整代码。我已经创建了一个工作小提琴,我会尝试解释这个过程。

首先,您有许多具有相同id. Id 必须是唯一的。其次,我添加了属性name,因为如果您提交表单,它会派上用场。

然后你需要监听change单选按钮上的事件。

这是代码:

HTML

<input type="radio" name="choice" value="fruit" checked="checked" />Favorite fruit?<br />
<input type="radio" name="choice" value="color" />Favorite color?<br />
<input type="radio" name="choice" value="sport" />Favorite sport?<br />

<div id="fruit">
  <input type="checkbox" value="apple"> Apple<br />
  <input type="checkbox" value="apple"> Banana<br />
  <input type="checkbox" value="apple"> Mango<br />
</div>

<div id="color">
  <input type="checkbox" value="black"> Black<br />
  <input type="checkbox" value="orange"> Orange<br />
  <input type="checkbox" value="blue"> Blue<br />
</div>

<div id="sport">
  <input type="checkbox" value="boxing"> Boxing<br />
  <input type="checkbox" value="cricket"> Cricket<br />
  <input type="checkbox" value="football"> Football<br />
</div>

CSS

div {
  display: none;
}

JS

//listen to a change on all radio buttons with the name "choice"
$('input[name="choice"]').on('change', function() {
  var t = $(this); //save this for future reference... this is an optimisation trick if you need to access $(this) many times... in this case it's not necessary.
  $('[type="checkbox"]').prop('checked', false); //uncheck all checkboxes
  $('div').hide(); //hide all divs
  $('#' + t.val()).show(); //show the correct div which it's id is the same name as the radio's value.

});

$('[name="choice"]:checked').trigger('change'); // trigger the change on the checked item (so we have a visible div on first load).

推荐阅读