如何获取所选复选框的标签

时间:2018-10-05 20:19:25

标签: javascript checkbox

我想看看如何在选中这些复选框后仅返回标签。 这是代码:

np.random.choice()

1 个答案:

答案 0 :(得分:1)

您需要更正html语法(关闭元素等)。然后,您可以将click事件侦听器添加到您的输入中,检查它们是否被“选中”,并从父标签中获取标签文本。例如:

const inputs = document.querySelectorAll('input');
for (let i of inputs) {
  i.addEventListener('click', (event) => {
    let elem = event.target;
    if (elem.checked) {
      let label = elem.parentNode.textContent;
      console.log(label);
    }
  });
}
<label class="threeLabel">
  <input type="checkbox" id="chkBusinessActivityStore" name="Business" class="validate-reqchk-byname label: 'Business Activity'">
  &nbsp;&nbsp;Store
</label>
<label class="threeLabel">
  <input type="checkbox" id="chkBusinessActivityCoffeeShop" name="Business" class="validate-reqchk-byname label: 'Business Activity'">
  &nbsp;&nbsp;Coffee Shop
</label>
<label class="threeLabel">
  <input type="checkbox" id="chkBusinessActivityBar" name="Business" class="validate-reqchk-byname label: 'Business Activity'">
  &nbsp;&nbsp;Bar
</label>