循环遍历javascript中的复选框

时间:2014-07-08 21:33:00

标签: javascript arrays forms checkbox

我觉得我应该知道答案,但我无法理解。我有一个大表格,有些问题有复选框。我需要能够循环遍历该特定问题的每个复选框,对于要检查的复选框,我需要存储在数组中。由于使用现有代码,我被迫使用javascript。这是我尝试过的一个例子:

<input type="checkbox" name="CAT_Custom_15" id="CAT_Custom_15_0" value="Bareboat charters">
<input type="checkbox" name="CAT_Custom_15" id="CAT_Custom_15_1" value="charters">
<input type="checkbox" name="CAT_Custom_15" id="CAT_Custom_15_2" value="Ferry">

<script>
var theForm = document.getElementById( 'OMRForm' );
var i;
var selectArray = []; //initialise empty array
for (i = 0; i < theForm.CAT_Custom_15.length; i++) {
    if(theForm.CAT_Custom_15.elements[i].type == 'checkbox'){
         if(theForm.CAT_Custom_15.elements[i].checked == true){
            selectArray.push(theForm.CAT_Custom_15.elements[i].value);
            alert(theForm.CAT_Custom_15.elements[i].value);
         }
     }
}
</script>

我已经盯着这么久,以至于我确定我在某个地方犯了错误。请帮忙!

1 个答案:

答案 0 :(得分:2)

theForm.CAT_Custom_15本身就是包含<input> s的集合,而不是将它们放在.elements属性中。

因此,type条件应为:

if(theForm.CAT_Custom_15[i].type == 'checkbox'){

VS:

if(theForm.CAT_Custom_15.elements[i].type == 'checkbox'){

for (i = 0; i < theForm.CAT_Custom_15.length; i++) {
    if(theForm.CAT_Custom_15[i].type == 'checkbox'){
         if(theForm.CAT_Custom_15[i].checked == true){
            selectArray.push(theForm.CAT_Custom_15[i].value);
            alert(theForm.CAT_Custom_15[i].value);
         }
     }
}

http://jsfiddle.net/9w9T5/