Jump to content

Total from dynamic input boxes


pixelguy

Recommended Posts

I have a page that generates numbers inside a input box. Depending upon the record fetched (using Java and a db), the page may contain any number of input boxes with numbers in them. They are sequentially labelled, such as openInvoices[0].customerpaymentamt, with the number in brackets incrementing for each additional field. How do I go about having javascript display the total from each of these fields in a new input field, and have it update dynamically when someone alters the value in any of the fields?

Link to comment
Share on other sites

I think the way I would approach this is to put all of these dynamic inputs into a container div that has a particular id:

<div id="InputContainer">  <input type="text" id="input1" />  <input type="text" id="input2" />  <input type="text" id="input3" />  <input type="text" id="input4" /></div>

Then, I'd write a function that would get all the inputs that were in that container as an array and I'd loop through the array of inputs to get the values. I'd then check to see if the values actually stored numbers and, if they did, add the numbers together into a variable:

var sum = 0;var inputs = document.getElementById("InputContainer").getElementsByTagName("input");for(var i = 0; i < inputs.length; i++){	var num = parseFloat(inputs[i].value);	sum += (isNaN(num)) ? 0 : num;}return sum;

This function could be called each time a key was pressed in one of the input fields and you could use the return value from that function to set the innerHTML of some display div or the value of a different input element.

Link to comment
Share on other sites

Thanks for the help. Following your advice (and the code you supplied), I threw together this example. However, the returned sum isn't displaying. I'm sure I'm missing something simple, but being a js idiot I can't seem to figure it out:

<html>	<head><script type="text/javascript">				function totalPayment () {	var sum = 0;	var inputs = document.getElementById("InputContainer").getElementsByTagName("input");	for(var i = 0; i < inputs.length; i++)		{	var num = parseFloat(inputs[i].value);	sum += (isNaN(num)) ? 0 : num;	}	return sum;	document.getElementById(total).innerHTML = sum;}						</script>	</head>	<body>	<div id="InputContainer">  <input type="text" id="input1" value="100"/>  <input type="text" id="input2" value="300"/>  <input type="text" id="input3" value="200"/>  <input type="text" id="input4" value="500"/>  <h1 id="total"></h1>	</div>	<input type="submit" onclick="totalPayment()"></input>	</body></html>

I think the way I would approach this is to put all of these dynamic inputs into a container div that has a particular id:
<div id="InputContainer">  <input type="text" id="input1" />  <input type="text" id="input2" />  <input type="text" id="input3" />  <input type="text" id="input4" /></div>

Then, I'd write a function that would get all the inputs that were in that container as an array and I'd loop through the array of inputs to get the values. I'd then check to see if the values actually stored numbers and, if they did, add the numbers together into a variable:

var sum = 0;var inputs = document.getElementById("InputContainer").getElementsByTagName("input");for(var i = 0; i < inputs.length; i++){	var num = parseFloat(inputs[i].value);	sum += (isNaN(num)) ? 0 : num;}return sum;

This function could be called each time a key was pressed in one of the input fields and you could use the return value from that function to set the innerHTML of some display div or the value of a different input element.

Link to comment
Share on other sites

Remove the line below from the totalPayment function.

return sum;

Place quotes around the word total in this line.

document.getElementById("total").innerHTML = sum;

Remove </input> from the line.

<input type="submit" onclick="totalPayment()"></input>

Link to comment
Share on other sites

Thanks! That worked great. Now, how would I go about displaying the value in a input text box's value field? I tried adding the code below...

<input type="text" id="total">

... but that didn't work. Any ideas?

Remove the line below from the totalPayment function.
return sum;

Place quotes around the word total in this line.

document.getElementById("total").innerHTML = sum;

Remove </input> from the line.

<input type="submit" onclick="totalPayment()"></input>

Link to comment
Share on other sites

Now, how would I go about displaying the value in a input text box's value field?
Using the DOM, you can set the value of an input similar to how you get the value from an input using the value property. To set the value of an input that has an ID of "total" you can do this:
document.getElementById("total").value = sum;

Link to comment
Share on other sites

One strange thing is that when I assign the total to an input box with the id of total, any re-running of the script (either through onclick or onload) keeps adding the totals to the previous total, which is not what I want.I'm assuming that this is because of either of these two lines:

 for(var i = 0; i < inputs.length; i++)

... or ..

 var num = parseFloat(inputs[i].value);

Is the "inputs.length" or the "inputs.value" pulling in the value from the input box with the id of total, and if so, how can the above be rewritten to pull the values just form the input boxes with the ids of input1, input2, and so on....?

Using the DOM, you can set the value of an input similar to how you get the value from an input using the value property. To set the value of an input that has an ID of "total" you can do this:
document.getElementById("total").value = sum;

Link to comment
Share on other sites

Try setting up your HTML like this:

<div id="InputContainer">  <input type="text" id="input1" />  <input type="text" id="input2" />  <input type="text" id="input3" />  <input type="text" id="input4" /></div><input type="text" id="total" />

That way, you can easily get at all the inputs that you want to use for the summation without getting the input used to display the total:

var inputs = document.getElementById("InputContainer").getElementsByTagName("input");

Link to comment
Share on other sites

Thanks, that makes sense. I also found that put this line of code at the top of the function works as well:

	document.getElementById("totalvalue").value = 0;

"totalvalue" being the input box that is displaying the total value.However, I'm trying to figure out if this is even possible. These total value needs to be submitted to another page as a value. The other page (this is all in java) will then process that value. But looking at the code, the total appears in the input box, but there is no value applied to the tag. Is javascript capable of putting the total in the value field in the code, or is this something I would need to do on the server side?

Try setting up your HTML like this:
<div id="InputContainer">  <input type="text" id="input1" />  <input type="text" id="input2" />  <input type="text" id="input3" />  <input type="text" id="input4" /></div><input type="text" id="total" />

That way, you can easily get at all the inputs that you want to use for the summation without getting the input used to display the total:

var inputs = document.getElementById("InputContainer").getElementsByTagName("input");

Link to comment
Share on other sites

When you change the value of the input using javascript, you are actually making that change directly to the DOM. When the form is submitted, the current value, whatever that may be, is sent to the server. It acts the same way as when a user types in a new value into the input field and hits submit.If you perform the function to calculate the sum before the form is submitted, then on the server, you can simply get the value of the total field to see what the sum is. In PHP, it'd look something like:

$sum = $_GET['total']

In C# (ASP.NET):

float sum;float.TryParse(Request["total"], out sum);

In any case, the data will be in the HTTP Request that is sent to the server.

Link to comment
Share on other sites

OK, here's a twist. The solution works well, but the app has to insert some hidden input tags for the next page to process. These tags contain values of dates and invoice numbers... Which are getting added to the total.Do you know of any way to exclude hidden input fields from being added to the total?

Link to comment
Share on other sites

Do you know of any way to exclude hidden input fields from being added to the total?
Just keep them out of that container div. When you are getting all the inputs, you should only be getting the inputs that are in that container div.
<div id="InputsUsedForSummation">  <input type="text" />  <input type="text" />  <input type="text" />  <input type="text" /></div><input type="text" id="total" /><input type="hidden" id="hidden1" /><input type="hidden" id="hidden2" />

var inputs = document.getElementById("InputsUsedForSummation").getElementsByTagName("input");

Alternatively, a less ideal solution would be to get all the inputs that are on the page and only use the inputs that are of type "text":

var inputElements = document.getElementsByTagName("input");var inputs = new Array();for(var i = 0; i < inputElements.length; i++){	if(inputElements[i].type == "text")	{		inputs.push(inputElements[i]);	}}// "inputs" now has all input elements on the page that have a type = "text"

Link to comment
Share on other sites

I'm curious as to why the solution that uses the if statement to select on input elements == text is less ideal?Thanks so much - I've learned more form this exercise/thread about js than I have from the book I've been going through. One last question - is there any built-in js function that can limit the sum to no more (and no less) than two decimal places?

Just keep them out of that container div. When you are getting all the inputs, you should only be getting the inputs that are in that container div.
<div id="InputsUsedForSummation">  <input type="text" />  <input type="text" />  <input type="text" />  <input type="text" /></div><input type="text" id="total" /><input type="hidden" id="hidden1" /><input type="hidden" id="hidden2" />

var inputs = document.getElementById("InputsUsedForSummation").getElementsByTagName("input");

Alternatively, a less ideal solution would be to get all the inputs that are on the page and only use the inputs that are of type "text":

var inputElements = document.getElementsByTagName("input");var inputs = new Array();for(var i = 0; i < inputElements.length; i++){	if(inputElements[i].type == "text")	{		inputs.push(inputElements[i]);	}}// "inputs" now has all input elements on the page that have a type = "text"

Link to comment
Share on other sites

I'm curious as to why the solution that uses the if statement to select on input elements == text is less ideal?
If you got all the inputs on the page, you would be getting input texts, submits, resets, images, hiddens, and passwords. Then you'd have to loop through and check for each one to see if it is of the appropriate type. Then, if you had more input texts on the page than the ones used for summation and the one used to display the total, you'd have to come up with a way to differentiate those from the addition function.Putting only the summation input texts in that div makes it much easier to get at them through the DOM.
One last question - is there any built-in js function that can limit the sum to no more (and no less) than two decimal places?
Hmm, I'm not aware of any built-in functions like that. Typically, if I want to round out to two decimal places, I multiply the number by 100, then round the number, and then divide the number by 100. Then, you have to check to see if there are two digits after the decimal and, if not, pad the number with zeros.For example, if the number was 145.2, you'd have to check to see if there are two digits after the decimal, since there isn't you'd have to add one to the end (pad): 145.20.Check out the Math and String references here for more help with that:http://www.w3schools.com/jsref/jsref_obj_math.asphttp://www.w3schools.com/jsref/jsref_obj_string.aspEDIT: Hah, this Google search proved me wrong - there is a built-in method: toFixed(2) will format a number so that it has two decimal places.
Thanks so much - I've learned more form this exercise/thread about js than I have from the book I've been going through.
Happy to have helped!
Link to comment
Share on other sites

For those of you following at home, here is the completed script:

function totalPayment () {	document.getElementById("totalvalue").value = 0;	var sum = 0;		var inputElements = document.getElementsByTagName("input");	var inputs = new Array();		for(var i = 0; i < inputElements.length; i++)		{	if(inputElements[i].type == "text")		{				inputs.push(inputElements[i]);			var num = parseFloat(inputElements[i].value);			sum += (isNaN(num)) ? 0 : num;		}	}document.getElementById("totalvalue").value = sum.toFixed(2);}

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...