superdan_35 Posted May 14, 2009 Share Posted May 14, 2009 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 Quote Link to comment https://forums.phpfreaks.com/topic/158088-solved-adding-textboxes-together-and-displaying-the-result-in-another-textbox/ Share on other sites More sharing options...
Axeia Posted May 14, 2009 Share Posted May 14, 2009 <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' /> Quote Link to comment https://forums.phpfreaks.com/topic/158088-solved-adding-textboxes-together-and-displaying-the-result-in-another-textbox/#findComment-834270 Share on other sites More sharing options...
superdan_35 Posted May 14, 2009 Author Share Posted May 14, 2009 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 Quote Link to comment https://forums.phpfreaks.com/topic/158088-solved-adding-textboxes-together-and-displaying-the-result-in-another-textbox/#findComment-834379 Share on other sites More sharing options...
Axeia Posted May 15, 2009 Share Posted May 15, 2009 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 Quote Link to comment https://forums.phpfreaks.com/topic/158088-solved-adding-textboxes-together-and-displaying-the-result-in-another-textbox/#findComment-834579 Share on other sites More sharing options...
superdan_35 Posted May 15, 2009 Author Share Posted May 15, 2009 Genius, thanks very much. Dan Quote Link to comment https://forums.phpfreaks.com/topic/158088-solved-adding-textboxes-together-and-displaying-the-result-in-another-textbox/#findComment-834613 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.