I have an order form and a JavaScript which should calculate grand total from textbox (quantity*price), checkbox and radio, but I’m missing something because i receive a NaN error. Could somebody help me fix it?
Thanks a lot.
I have an order form and a JavaScript which should calculate grand total from
Share
Like many have commented, there are some serious short-comings to your code. I won’t re-iterate these concerns, however, they are very important and you should learn as you are getting more acquainted with the technologies you are using.
The reason you are getting a NaN is this. Your fields object is an array. Your code populates the fields array at an arbitrary indices, i.e. fields[f] = 0;
When you populate the array for index, say 5, your code does this fields[5] = 0;. With this statement you went from having an empty array [], to having an array with 6 entries with the first 5 entries being defaulted to undefined [undefined, undefined, undefined, undefined, undefined, 0].
Now later in your code when you do the summation and add the arrays entries up (using eval having prepared a string) these …undefined+0+undefined+8… are producing a Not A Number error.
Instead, one way to prevent this is to push entries onto the fields array like:
push will add one entry to the end of the array. [] will become [0] if you push(0).