Jump to content

[SOLVED] Adding textboxes together and displaying the result in another textbox


superdan_35

Recommended Posts

Hi all.

 

I have a form with 5 text boxes for the user to enter numbers. I would like to have a sixth text box at the end that adds up the total of all the other inputs.

 

I assume that this can be done and will require javascripting or AJAX? The page is built in php and ideally I would like it to be done without the page reloading, hence the javascript.

 

Thanks,

Dan

<script type='text/javascript'>
function notifyChange()
{
  var theSum = 0;
  for( var i = 1; i <= 5; i++ ) 
  {
    var field = document.getElementById( 'val'+i );
    if( isNaN( field.value ) )
      alert( 'Sorry, all values have to numeric!' );
    else
      theSum += parseInt( field.value );
  }
  document.getElementById( 'sum' ).value = theSum;
}
</script>
<input onchange="notifyChange()" id='val1' />
<input onchange="notifyChange()" id='val2' />
<input onchange="notifyChange()" id='val3' />
<input onchange="notifyChange()" id='val4' />
<input onchange="notifyChange()" id='val5' />
<input id='sum' />

Wow, that's fantastic.

Thanks very much for the quick reply.

 

Not so much a problem, but is there anyway to avoid the result in the final box being NaN until all boxes are complete, or in other words, not requiring input into all the boxes?

 

Thanks again,

Dan

With a little bit ternary operator magic it can be done.

Chang the else statement to

theSum += field.value == '' ? 0 : parseInt( field.value );

 

Oh and if you need calculations like 1.3 + 1.5 instead of parseInt use parseFloat

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.