如何使用JavaScript为以下HTML获取选中的复选框。 我的所有复选框都有ID,如下所示,如HTML
所示SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0
SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1
// ... and so on, up to
SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_n
我尝试使用以下代码
var IDtoFind="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_"
var txts = document.getElementsByTagName('input');
for (var i = 0; i < txts.length; ++i) {
if (txts[i].name.indexOf(IDtoFind)!=-1) {
if(txts[i].checked){ alert(txts[i].id); }
// targetId = txts[i].id;
}
}
&#13;
但它不起作用。我想得到复选框标签的文本
<table id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceTable" cellpadding="0" cellspacing="1">
<tbody>
<tr>
<td>
<span class="ms-RadioText" title="NO SECURITY ISSUE Observed">
<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0" type="checkbox" checked="checked">
<label for="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0">NO SECURITY ISSUE Observed</label>
</span>
</td>
</tr>
<tr>
<td>
<span class="ms-RadioText" title="Staff NOT wearing identification / name badge">
<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1" type="checkbox">
<label for="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1">Staff NOT wearing identification / name badge</label>
</span>
</td>
</tr>
</tbody>
</table>
&#13;
答案 0 :(得分:0)
您可以使用nextelementsibling属性,如
function get() {
var inputs = document.querySelectorAll('input[type="checkbox"][id^="SECURITY_"]'),
labels = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
labels.push(inputs[i].nextElementSibling.innerHTML.trim())
}
}
alert(labels)
}
<table id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceTable" cellpadding="0" cellspacing="1">
<tbody>
<tr>
<td>
<span class="ms-RadioText" title="NO SECURITY ISSUE Observed">
<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0" type="checkbox" checked="checked">
<label for="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0">NO SECURITY ISSUE Observed</label>
</span>
</td>
</tr>
<tr>
<td>
<span class="ms-RadioText" title="Staff NOT wearing identification / name badge">
<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1" type="checkbox">
<label for="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1">Staff NOT wearing identification / name badge</label>
</span>
</td>
</tr>
</tbody>
</table>
<button onclick="get()">Get</button>
注意:如果您可以向这些复选框添加类
,则可以简化复选框选择器<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0" type="checkbox" checked="checked" class="security-multichoiceoption"/>
然后
inputs = document.getElementsByClassName('security-multichoiceoption')
答案 1 :(得分:0)
here
我做了一个演示,返回一个加工对象的数组,你可以通过使用那些函数简单地到达元素,它返回一个数组,所以those()[0].id
将只返回第一个选定元素的id