April 9th, 2013, 06:46 AM
Adding different values of different input types
I'm trying to make a registration form, and one part of that is it needs to be able to add the values of input types and displays it at the bottom.
This is what I've done for the JS;
var total = 0;
var price; var i;
total = total + eval(obj.value);
total = total - eval(obj.value);
var pro = 0;
var price; var i;
pro = pro + eval(obj.value);
pro = pro - eval(obj.value);
//Calculates total cost
var totalCost = ShowTotal() + ShowProTotal();
document.getElementById("regform").cost.value = totalCost;
And this is the HTML parts of it which are affected by it;
<input name="attend" value="50.00" type="checkbox" onclick="getTotal()" />Monday
<input name="attend" value="50.00" type="checkbox" onclick="getTotal()" />Tuesday
<input name="attend" value="50.00" type="checkbox" onclick="getTotal()" />Wednesday
<input name="proceedings" value="50" type="radio" checked="checked" onclick="getTotal();" />Yes
<input name="proceedings" value="0" type="radio" onclick="getTotal();" />No
//Where result should be displayed
<input id="cost" name="cost" class="formtextfield" type="text" />
I've omitted the rest of the code out for clarity, I'm not entirely sure where the problem is because when I try it with just the Checkbox it seems to be displaying the result fine. I'm probably doing something very wrong with the funtions.
Any help on this would be very much appreciated. Thanks
April 9th, 2013, 07:55 AM
first of all: Congratulations on using the [ CODE ] tags in the first post. That's rare.
Your ShowTotal() and ShowProTotal() function expect an object as the argument, but you don't pass anything when calling them. You use the return values of the function, but they don't have any return value. And what is the eval() supposed to do?? Don't use eval() unless you really, truly know what you're doing.
I think it might be a good idea to start from scratch. Before you start writing down code, make of concept of what you wanna do and how you wanna implement it. While you program, test each functionality before moving on to the next one. This way you'll notice errors very early and don't end up with a whole script of broken code.
By the way, is there any reason why you distinguish between ShowTotal() and ShowProTotal()? In the code you posted, it's completely useless, because you add up the values, anyway.
Personally, I'd approach this in a different way: Make a single function for calculating the total and bind it to the "onchange" event of the input fields. In the function, loop through all fields and add up the values (you only need to account for checked boxes). After that, display the total.