Forum Moderators: open

Message Too Old, No Replies

Javascript Checkbox Loop Error

Firebug gives me an undefined error, when it's clearly defined.

         

code junkie8

8:26 pm on Jun 6, 2010 (gmt 0)

10+ Year Member



Alright, I made a function to get the values of checked checkboxes to collect and in further development of the function, I will pass data through AJAX.

Anyways, continuing on, here's my function:


function generate_email (form_name, field_name, type) {
var check_box_field = document.forms[form_name].elements[field_name];
var check_box_count = check_box_field.length;
var user_ids;

for (var i = 0; i <= check_box_count; i++) {
if (check_box_field[i].checked) { //
if (check_box_count != (i + 1))
user_ids += check_box_field[i].value + ",";
else
user_ids += check_box_field[i].value;
}
}
}


The error that Firebug generates is:


check_box_field[i] is undefined
- user_ids += check_box_field[i].value + ",";


Thanks in advance!

- code_junkie8

Fotiman

8:48 pm on Jun 6, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Welcome to WebmasterWorld!

Your for loop is incorrect. You have:

for (var i = 0; i <= check_box_count; i++) {

It should be:

for (var i = 0; i < check_box_count; i++) {

Otherwise, when i == check_box_count you then if you try to access check_box_field[i] you will be stepping past the end of the array. An array of 10 items is accessed using indexes 0 through 9, so if you try to access it with index 10, you've gone too far.

Hope that helps.

code junkie8

10:05 pm on Jun 6, 2010 (gmt 0)

10+ Year Member



Awesome, that fixed it. I had "var i = 1;" at first because of the count's max number, but I thought, "Hey, that's dumb because arrays start at 0" and I never changed it back. Thanks Fotiman! :)