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

Link to comment
Share on other sites

<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' />

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.