表单的复选框是用以下html以编程方式创建的:
<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
的复选框的状态。
发布于 2018-06-13 05:50:16
如果您对VanillaJS解决方案感兴趣,可以使用document.querySelectorAll
。
// 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`);
});
});
<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>
发布于 2018-06-13 05:52:03
复选框是否始终位于DOM树中的同一位置?
如果是这样,您可以使用CSS层次结构和伪选择器来检索第n个元素:
$("#myform div:nth(n) input")[0].checked
https://stackoverflow.com/questions/50826092
复制相似问题