2

I feel like I should know the answer but I just can't get it. I have a big form and some questions have checkboxes. I need to be able to loop through each of the checkboxes for that particular question and for the ones that're checked, I need to store in an array. I'm forced to use javascript due to working with existing code. here's one example I've tried:

<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>

I've stared at this so long it that I'm sure i've made a mistake somewhere. Please help!

1
  • It most likely is, I've referenced them but still couldn't get my code working. Which is why I'm posting here. Commented Jul 8, 2014 at 21:37

1 Answer 1

2

theForm.CAT_Custom_15 is itself the collection containing the <input>s rather than having them in an .elements property.

So, the type condition, for example, should be:

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/

Sign up to request clarification or add additional context in comments.

1 Comment

haha, I can't believe I didn't see that. That was all that's needed. I just ran a test and it's displaying all the checked checkboxes. You are a life saver man. I'll be able to make the deadline now! If we ever meet, I'll buy you a beer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.