首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在给定文本的情况下获取复选框的状态

在给定文本的情况下获取复选框的状态
EN

Stack Overflow用户
提问于 2018-06-13 05:29:37
回答 2查看 46关注 0票数 0

表单的复选框是用以下html以编程方式创建的:

代码语言:javascript
复制
<div class="checkbox"><label for="household_assistances_10"><input id="household_assistances_10" name="household[assistances][]" value="10" type="checkbox">Other</label></div>

假设id是唯一的,但它的数字(例如,10)无法预测,如何确定是否选中该框?我尝试过各种各样的选择器,但还没有成功。

编辑:

显然不清楚我是否需要遵循显示为Other的复选框的状态。

EN

回答 2

Stack Overflow用户

发布于 2018-06-13 05:50:16

如果您对VanillaJS解决方案感兴趣,可以使用document.querySelectorAll

代码语言:javascript
复制
// For the purpose of this example - attach click event to the button element
document.getElementById('button').addEventListener('click', function(event) {

  // Get all checkboxes
  const checkboxes = document.querySelectorAll('input[type="checkbox"]');

  // Consider using map instead of forEach
  // Iterate over the checkboxes
  checkboxes.forEach(checkbox => {
  
    // Do something with each checkbox
    const isChecked = checkbox.checked;
    const id = checkbox.id;

    console.log(`Checkbox ${id} ${isChecked ? 'is' : 'is not'} checked`);
    
  });

});
代码语言:javascript
复制
<div class="checkbox">
  <label for="household_assistances_8">
    <input
      id="household_assistances_8" 
      name="household[assistances][]"
      value="10"
      type="checkbox"
    />
    Other
  </label>
  <label for="household_assistances_9">
    <input
      id="household_assistances_9" 
      name="household[assistances][]"
      value="9"
      type="checkbox"
    />
    Other
  </label>
  <label for="household_assistances_10">
    <input
      id="household_assistances_10" 
      name="household[assistances][]"
      value="10"
      type="checkbox"
    />
    Other
  </label>
  <input type="button" id="button" value="button"/>
</div>

票数 0
EN

Stack Overflow用户

发布于 2018-06-13 05:52:03

复选框是否始终位于DOM树中的同一位置?

如果是这样,您可以使用CSS层次结构和伪选择器来检索第n个元素:

代码语言:javascript
复制
$("#myform div:nth(n) input")[0].checked
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50826092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档