PDA

View Full Version : DOM-generated input not taking name method



Opally
Sep 10th, 2007, 11:05 PM
Howdy!

I think there is a problem with my dynamically generated input fields and checkbox in my form: although I am giving them a name, when I experimentally examine the code, the name is something bogus. This is causing my JS subtotal calculation script to fail, as "error: elements[...].checked is null or not an object."

EDIT: the bogus name is only happening in Internet Explorer. My inspection of the DOM in FireFox shows me that the fields are being added correctly. But there is still the error.

The checkbox indicates that a registrant is attending and paying for an optional reception ticket.

If I run the script on my one non-dynamic checkbox (set maxNum = 1) it works fine.

My javascript for performing a calculation depending on the presence of checked boxes:


for (var i = 0; i < maxNum; i++) {
var myform = document.regisform;
if (myform.elements["regisrecep" + i].checked == true) {
subtot = subtot + 15;
}
}


The above script produces a "myform.elements["regisrecep" + i] has no properties" error in Firebug (Mozilla add-on.)

My javascript for generating the checkbox looks like this:


var newRecep = document.createElement('input');
newRecep.type = 'checkbox';
newRecep.name = 'regisrecep' + rowCount;
newRecep.id = 'regisrecep' + rowCount;
document.getElementById('groupreg').appendChild(newRecep);



You can see the form here (https://www.coreknowledge.org/secure/html_forms/confregform_mod.php).

anxious to hear the wisdom of the Javascript sages.

---Opally

rwedge
Sep 11th, 2007, 12:40 AM
Since the loop runs 30 times and you may not have that many checkboxes added, you will need to see if the checkbox element exists before checking to see if it is checked.

example with getElementById
for (var i = 0; i < maxNum; i++) {
var chkbox = document.getElementById('regisrecep' + i);
if (chkbox && chkbox.checked) {
subtot = subtot + 15;
}
}

Opally
Sep 11th, 2007, 04:44 PM
you're a genius, thank you rwedge!

I'm learning, I'm learning!

---opal