So I have a form with a bunch of Text fields. Some of the fields are related and I need to loop through them and add up the numbers in the value field.
The fields are all named differently so I can tell them apart so I'm not sure how to look through them.
Can I set them all to the same ID or same something to then do the loop based on the shared property? I'd rather not have to manually go through them all but can do that if I have to.
I guess maybe if all the fields are part of a form array I can figure out where the fields I want start and stop and loop them that way? hmmm
Native JavaScript is much simpler. A form node is an array of all its named controls, as well as an object with attributes.
The named controls are described in the HTML5 spec and in the HTML 4.01 one.
The W3C solution is quite elegant.
var form = document.querySelectorAll( 'form' )[0];
var total = 0;
for (var i = 0; i < form.length; i++) {
console.log( form[i] );
total += parseInt( form[i].value );
}
There's no need for libraries. The only downside is that fieldsets in the form are iterated through as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With