I am trying to figure out how to add up a series of text boxes which contain numbers that a user will input and have the total of those text boxes show up in a quantity text box on the next page.

Not sure if i should use javascript or php, but i don't know how to do it either, so any help would be appreciated.

thanks, nigel

Dani AI

Generated

Good starting advice from and a helpful warning from about parseInt — both points can be combined into a simple, robust workflow that keeps the UX pleasant and the server-side data trustworthy.

Client-side + form-submit (recommended for immediate feedback): mark each quantity input with a shared class/name (for example name="qty[]" class="qty"), show a live total, and keep one hidden input that is updated right before submit. Live-conversion should use Number() or parseFloat() (not plain parseInt unless an integer with explicit radix is intended) and fall back to zero for empty/invalid values. Using <input type="number"> helps with input UI/validation but server-side validation is still required. (developer.mozilla.org)

Example client-side pattern:

function sumQtys(selector) {
  return Array.from(document.querySelectorAll(selector)).reduce((s, el) => {
    const v = (el.value || '').trim().replace(',', '.');
    const n = Number(v);
    return s + (Number.isNaN(n) ? 0 : n);
  }, 0);
}

const form = document.querySelector('#orderForm');
const hiddenTotal = document.querySelector('#totalHidden');
form.addEventListener('input', () => {
  document.querySelector('#displayTotal').textContent = sumQtys('input.qty');
});
form.addEventListener('submit', () => {
  hiddenTotal.value = sumQtys('input.qty');
});

Always re-calculate on the server (trust nothing from the client). If posting name="qty[]", loop the array and sum with floatval() (or equivalent) in PHP; return the canonical total to display on the next page. Client-side totals are convenience only. (developer.mozilla.org)

Troubleshooting & alternatives: use readonly instead of disabled if a prefilled control must be submitted (disabled controls are not sent). If the next page must be reached without a form submit, sessionStorage/localStorage can carry the total between pages. If parseInt is used, always pass the radix (e.g. parseInt(s,10)) to avoid historical edge cases. (developer.mozilla.org)

Recommended Answers

All 5 Replies

First, you have to give each box an ID that you can easily use in a do-loop [for example, score1, score2, score3...] You also need to have a page element with the ID 'Total'. Here, FWIW, is what I have in my code (I happen to have 13 boxes):

function totalscore(){//set array containing scores
		chemtests = new Array();
		for(var i=0; i<13; i++){ 
			rownumber = i+1;	
			myscore=parseInt(document.getElementById('score' + (rownumber)).innerHTML)
			chemtests[i]=myscore
		}//end for loop
		//add up scores and stick them into the total box
		var sum = 0;
		for(var i=0; i<13; i++){
			sum=sum + parseInt(chemtests[i]);
		}
		document.getElementById('Total').innerHTML=sum
	}

Test this and see if it works for you. Also, I took out a few lines with irrelevant code, so make sure the brackets all match.

my apologies Scott, I thought I would get an email if someone answered my thread. I will try this out. So sorry I didn't get back sooner.

sum=sum + parseInt(chemtests[i]);

In that portion, use

sum=sum + parseInt(chemtests[i], 10);

instead because the parseInt has a bug when the number has leading 0 in front. Forcing it with base 10 would solve the problem.

sum=sum + parseInt(chemtests[i]);

In that portion, use

sum=sum + parseInt(chemtests[i], 10);

instead because the parseInt has a bug when the number has leading 0 in front. Forcing it with base 10 would solve the problem.

Thanks! So far, that bug hasn't bitten me yet, but I'll be on the lookout for it. The leading zero shouldn't be an issue, though, since the boxes are populated by another script, not by user input. For the original poster, though, it's a possibility to be reckoned with!

BTW, is this a universal problem, or just one with a specific Javascript implementation?

my apologies Scott, I thought I would get an email if someone answered my thread. I will try this out. So sorry I didn't get back sooner.

That's odd. I got an e-mail notifying me about your reply. Go figure (spam filters and company firewalls often seem to interfere with email).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.