Adding numbers in javascript/Ajax

Hi,
I have what is essentially a small spread sheet on a web page.
I want to total the numbers in the rows and then total the numbers in the columns.
I was going to use Ajax with a server side script. But then I realized I don't really need a server side script to add the numbers, I can do that just in javascript, the calculation is very simple.
But then I realized I don't know how to do it in Javascript!  The thing I'm not sure about is how to use the innerHTML properly to insert values into several different fields.
I'll attach a screen shot and some code. The code wasn't written for this, I wrote it for something totally different, I was just about to start adapting it.

So, in an nutshell, I need a simple javascript that will add the row (front desk, assistant, sick, etc...)  up and display it in the "Total" column. I'll want to do that for multiple rows at the same time. I'm guessing it's pretty easy in JS?
Thanks!
Nacht



Here is the code from a previous JS I wrote for something else:
-------------------------------------------------------
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {

try {
        XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) { // Create the older type instead:
        try {
        XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) { }
     }

}
function checkNumber()
{

if(XMLHttpRequestObject) {
var guid = document.getElementById('guid').value;


// 1
var ac1 = document.getElementById('areacode1').value;
var prefix1 = document.getElementById('prefix1').value;
var number1 = document.getElementById('number1').value;

// 2
var ac2 = document.getElementById('areacode2').value;
var prefix2 = document.getElementById('prefix2').value;
var number2 = document.getElementById('number2').value;

// 3
var ac3 = document.getElementById('areacode3').value;
var prefix3 = document.getElementById('prefix3').value;
var number3 = document.getElementById('number3').value;

// 4
var ac4 = document.getElementById('areacode4').value;
var prefix4 = document.getElementById('prefix4').value;
var number4 = document.getElementById('number4').value;

// 5
var ac5 = document.getElementById('areacode5').value;
var prefix5 = document.getElementById('prefix5').value;
var number5 = document.getElementById('number5').value;

// 6
var ac6 = document.getElementById('areacode6').value;
var prefix6 = document.getElementById('prefix6').value;
var number6 = document.getElementById('number6').value;

// 7
var ac7 = document.getElementById('areacode7').value;
var prefix7 = document.getElementById('prefix7').value;
var number7 = document.getElementById('number7').value;

//8
var ac8 = document.getElementById('areacode8').value;
var prefix8 = document.getElementById('prefix8').value;
var number8 = document.getElementById('number8').value;

//9
var ac9 = document.getElementById('areacode9').value;
var prefix9 = document.getElementById('prefix9').value;
var number9 = document.getElementById('number9').value;



var url = "/x/dnc.pl";
var param = ".State=SEARCH&areacode1="+ escape(ac1) + "&prefix1=" + escape(prefix1) + "&number1=" + escape(number1) + "&areacode2="+ escape(ac2) + "&prefix2=" + escape(prefix2) + "&number2=" + escape(number2)
+ "&areacode3="+ escape(ac3) + "&prefix3="+ escape(prefix3) + "&number3=" + escape(number3) + "&areacode4="+ escape(ac4) + "&prefix4="+ escape(prefix4) + "&number4=" + escape(number4)
+ "&areacode5="+ escape(ac5) + "&prefix5="+ escape(prefix5) + "&number5=" + escape(number5) + "&areacode6="+ escape(ac6) + "&prefix6="+ escape(prefix6) + "&number6=" + escape(number6) + "&areacode7="+ escape(ac7) + "&prefix7="+ escape(prefix7) + "&number7=" + escape(number7) + "&areacode8="+ escape(ac8) + "&prefix8="+ escape(prefix8) + "&number8=" + escape(number8) + "&areacode9="+ escape(ac9) + "&prefix9="+ escape(prefix9) + "&number9=" + escape(number9) + "&guid=" + escape(guid);
//alert(param);
XMLHttpRequestObject.open("POST", url);
XMLHttpRequestObject.onreadystatechange = handleResponse
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.send(param);
}
}

function handleResponse() {

var obj = document.getElementById('searchresult');
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
//alert(XMLHttpRequestObject.status);
obj.innerHTML = XMLHttpRequestObject.responseText;
}
} // end Handle Response

Open in new window

Screen-shot-2013-11-26-at-9.38.0.png
LVL 1
nachtmskAsked:
Who is Participating?
 
Pierre CorneliusConnect With a Mentor Commented:
I put together a quick rough demo for you to illustrate using the rows and columns in the table and setting the value of your total column. I just used my own table based on the picture you posted.

<!DOCTYPE html> 
<html>
<body>
	<table id="tblHours" border="1px">
		<tr><th>Name</th><th colspan="6">Hours</th></tr>
		<tr>
			<th></th>
			<th>Front Desk</th>
			<th>Assistant</th>
			<th>Sick</th>
			<th>Vacation</th>
			<th>Other</th>
			<th>Total</th>
		</tr>
		
		<tr>
			<td>Employee1</td>
			<td>1</td>
			<td>2</td>
			<td>3</td>
			<td>4</td>
			<td>5</td>
			<td></td>
		</tr>
		
		<tr>
			<td>Employee2</td>
			<td>10</td>
			<td>20</td>
			<td>30</td>
			<td>40</td>
			<td>50</td>
			<td></td>
		</tr>
		
		<tr>
			<td>Employee3</td>
			<td>100</td>
			<td>200</td>
			<td>300</td>
			<td>400</td>
			<td>500</td>
			<td></td>
		</tr>
	</table>
	
	<script>
		function AddTotals() 
		{
			var col;
			var t;
			var rows = document.getElementById('tblHours').rows;
			for (var ri=2; ri<rows.length; ri++)
			{
				t=0;
				for (col=1; col<6; col++)
				{
				  t+= parseInt(rows[ri].cells[col].innerHTML);
				}
				rows[ri].cells[6].innerHTML = t;
			}
			
		}
		AddTotals();
	</script>
</body>
</html>

Open in new window

0
 
leakim971PluritechnicianCommented:
please post HTML for a row
0
 
nachtmskAuthor Commented:
Sure, here is one row:
The value in each input box has to be a real number.
<tr>
<td>
<select name="empname" size="1" id="empname">
<option value=0 SELECTED> Select Employee </option>
<option value="122" >John Lennon</option>
<option value="120" >Paul McCartney</option>
<option value="121" >George Harrison</option>
<option value="123" >Ringo Starr</option>
</select></td>
<td><input type="text" name="frontdesk" id="frontdesk" size="8"/></td>
<td><input type="text" name="assistant" id="assistant" size="8"/></td>
<td><input type="text" name="sick" id="sick" size="8"/></td>
<td><input type="text" name="vacation" id="vacation" size="8"/></td>
<td><input type="text" name="other" id="other" size="8"/></td>
<td><div class="total" id="total"></div></td>
</tr>

Thanks
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
nachtmskAuthor Commented:
Thanks Pierre, that helped a great deal.
I changed the parseInt to parseFloat to handle real numbers.
Question though, if one of the fields is left blank, then the result I'm getting is "Nan", which I assume is Not a Number. I'd rather not have my users be required to enter something into every field.
What do you think an elegant way to handle that would be?
0
 
leakim971Connect With a Mentor PluritechnicianCommented:
Here a jQuery version : http://jsfiddle.net/HKCMC/1/

$(document).ready(function() {

    $(":text", "#myTableID").bind("change blur paste", function() {
        var total = 0;
        var row = $(this).closest("tr");
        var textboxesOnTheRow = row.find(":text:not(:last)");
        textboxesOnTheRow.each(function(i, textbox) {
            total += $(this).val() * 1;
        });
        $(":text:last", row).val( total );
    });

    $("#myTableID tr").find(":text:first").trigger("change");
    
});

Open in new window


Question though, if one of the fields is left blank, then the result I'm getting is "Nan", which I assume is Not a Number. I'd rather not have my users be required to enter something into every field.

instead using << parseFloat >> or << parseInt >> use << * 1 >>
0
 
Pierre CorneliusCommented:
you could change the function as follows:

function AddTotals() 
		{
			var col;
			var t,v;
			var rows = document.getElementById('tblHours').rows;
			for (var ri=2; ri<rows.length; ri++)
			{
				t=0;
				for (col=1; col<6; col++)
				{
				  v = parseFloat(rows[ri].cells[col].innerHTML);
				  t+= isNaN(v) ? 0.00: v;				  
				}
				rows[ri].cells[6].innerHTML = t;
			}
			
		}

Open in new window

0
 
Pierre CorneliusCommented:
@leakim
from the code he posted, it does not look like he is using JQuery
0
 
nachtmskAuthor Commented:
Thanks,
Yeah, I'm not using Jquery, it's something I just did myself. I probably should use something like Jquery, but I generally don't. I find it easier to understand and debug if I write it myself.
0
 
VincentPugliaCommented:
Hi,

I have a question or two:
1)  are all your ids the same?  (total, frontdesk, etc)  If so, that will cause problems.
2) are you looking for a running, dynamic total?

you can use the onblur event handler in your input fields:

<input .... class='frontdesk' id='frontdesk1' onblur="add2Total(this.value, 1)";

where add2Total looks something like:

function add2Total(val, row) {
   var theTotal2add = "total" + row;
   total += Number(row);
  document.getElementById(theTotal2add).innerHTML = total;
}

the above will look for a global var "total" that should be reset to 0 with each row:

<select .... onselect="total = 0">
0
 
nachtmskAuthor Commented:
Vincent,
Thanks for the reply.
1. No, the ID's are all different.
2. It doesn't have to be dynamic. Once the user has entered in all rows, I have a  'calculate' button they press which triggers the summing up of numbers. If all is OK, I change the 'caculate' button to a 'submit' button.
The onBlur event is a nice idea though. I will keep that in mind.
0
 
VincentPugliaCommented:
how are your ids named?  (frontdesk1, frontdesk2...)?

if so,
<....button value="calculate" onclick="addTotals()">


function addTotals() {
   var total = 0;
    var divObj;
   var numberOfRows = 10;
   var columnNames = ['frontdesk', 'sick'.....];
   for (I = 0; I < numberOfRows; I++) {
        for (j = 0; j < columnNames.length; j++) {
            divObj = document.getElementById(columnNames[j] + i)
            total += Number(divObj.value);
        }
       document.getElementById ("total" + i).innerHTML = total;
       total = 0;
  }
}

did not test....
0
 
leakim971PluritechnicianCommented:
Yeah, I'm not using Jquery, it's something I just did myself. I probably should use something like Jquery, but I generally don't.

Open in new window


I know you're not using jQuery but here the jQuery equivalent code of your question.

function checkNumber()
{
    var url = "/x/dnc.pl";
    var param = $("form").serializeArray(); // Assuing all your fields are inside a form (guid too)
    $.extend(param,{name:".State", value:"SEARCH"});
    $.post(url,param, function(test_result) {
        $("#searchresult").html(test_result);
    });
}

Open in new window

0
 
nachtmskAuthor Commented:
I should get into jquery. Just don't have the time to learn something new it seems.
Thanks
0
 
leakim971PluritechnicianCommented:
you don't need to learn the language totally before using it.
you can mix it with simple javascript code, the following is valid for example :
// 1
var ac1 = document.getElementById('areacode1').value;
var prefix1 = document.getElementById('prefix1').value;
var number1 = document.getElementById('number1').value;

// 2
var ac2 = $('#areacode2').val();
var prefix2 = $('#prefix2').val();
var number2 = $('#number2').val();

Open in new window


IMHO :
if you know CSS, you know more than 20% of the language
if you know Javascript you know more than 50% of the language
Knowing CSS and Javascript you know 70% of jQuery language
0
 
VincentPugliaCommented:
Hi,
   
     Except for job requirements, I really don't see the need to learn jquery.  It doesn't really offer anything that can't be coded in vanilla javascript.  And, if you say it makes it faster & easier to code, that may be true, but only after the initial time spent learning.

  My philosophy in coding is: KISS (keep it simple, stupid) ... where  "stupid" == me, the coder.
0
 
nachtmskAuthor Commented:
LeaKim -- wow, didn't realize it was that simple.  When you show the example next to regular Javascript it makes perfect sense. Cool.
0
 
nachtmskAuthor Commented:
Vincent -- ha, I hear you.
My code is usually longer then most would write it because I write most things out the long way. Mostly so I can easily figure it out and (hopefully) modify it later. A few months down the line I'll forget what it was I was doing, even with comments!
Sometimes I like to learn new things and new ways of doing things just for fun. But when I actually need to finish something quickly, not so much.
No job requirement here, I can do it in any language/method I want, as long as it works!
0
 
leakim971PluritechnicianCommented:
var param = ".State=SEARCH&areacode1="+ escape(ac1) + "&prefix1=" + escape(prefix1) + "&number1=" + escape(number1) + "&areacode2="+ escape(ac2) + "&prefix2=" + escape(prefix2) + "&number2=" + escape(number2)
+ "&areacode3="+ escape(ac3) + "&prefix3="+ escape(prefix3) + "&number3=" + escape(number3) + "&areacode4="+ escape(ac4) + "&prefix4="+ escape(prefix4) + "&number4=" + escape(number4)
+ "&areacode5="+ escape(ac5) + "&prefix5="+ escape(prefix5) + "&number5=" + escape(number5) + "&areacode6="+ escape(ac6) + "&prefix6="+ escape(prefix6) + "&number6=" + escape(number6) + "&areacode7="+ escape(ac7) + "&prefix7="+ escape(prefix7) + "&number7=" + escape(number7) + "&areacode8="+ escape(ac8) + "&prefix8="+ escape(prefix8) + "&number8=" + escape(number8) + "&areacode9="+ escape(ac9) + "&prefix9="+ escape(prefix9) + "&number9=" + escape(number9) + "&guid=" + escape(guid);

Open in new window


is similar to :
var param = $("form").serialize(); // assuming ALL(guid included) your fields are inside a form

Open in new window


Yes, this time you need to know that, but if you don't know that, you can still use the old and "simple" method
0
 
leakim971PluritechnicianCommented:
fighting with cross browser ajax call?

This whole block :
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {

try {
        XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) { // Create the older type instead:
        try {
        XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) { }
     }

}

function handleResponse() {

var obj = document.getElementById('searchresult');
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
//alert(XMLHttpRequestObject.status);
obj.innerHTML = XMLHttpRequestObject.responseText;
}
} // end Handle Response

//alert(param);
XMLHttpRequestObject.open("POST", url);
XMLHttpRequestObject.onreadystatechange = handleResponse
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.send(param);

Open in new window


become this :
$.post(url, param, function(result) { $('#searchresult').html(result) }); 

Open in new window

0
 
leakim971PluritechnicianCommented:
Check this :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Q_28304068</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>

	function checkNumber()
	{
		var url = "/x/dnc.pl";
		var param = $("form").serializeArray(); // Assuing all your fields are inside a form (guid too)
		$.extend(param,{name:".State", value:"SEARCH"});
		$.post(url,param, function(test_result) {
			$("#searchresult").html(test_result);
		});
	}
	
	$(document).ready(function() {
	
		$(":text", "#myTableID").bind("change blur paste", function() {
			var total = 0;
			var row = $(this).closest("tr");
			var textboxesOnTheRow = row.find(":text:not(:last)");
			textboxesOnTheRow.each(function(i, textbox) {
				total += $(this).val() * 1;
			});
			$(":text:last", row).val( total );
		});
	
		$("#myTableID tr").find(":text:first").trigger("change");
		
		$("#but").click(checkNumber);
		
	});

</script>
</head>
<body>
<form>
    <input type="hidden" id="guid" name="guid" value="1234" />
    <input type="button" id="but" value="Check Number" /><span id="searchresult">SEARCH RESULT HERE</span>
    <table id="myTableID">
        <tr>
            <td>
            <select name="empname" size="1" id="empname">
            <option value=0 SELECTED> Select Employee </option>
            <option value="122" >John Lennon</option>
            <option value="120" >Paul McCartney</option>
            <option value="121" >George Harrison</option>
            <option value="123" >Ringo Starr</option>
            </select></td>
            <td><input type="text" name="frontdesk" id="frontdesk" size="8"/></td>
            <td><input type="text" name="assistant" id="assistant" size="8"/></td>
            <td><input type="text" name="sick" id="sick" size="8"/></td>
            <td><input type="text" name="vacation" id="vacation" size="8"/></td>
            <td><input type="text" name="other" id="other" size="8"/></td>
            <td><div class="total" id="total"></div></td>
        </tr>
        <tr>
            <td>
            <select name="empname" size="1" id="empname"1>
            <option value=0 SELECTED> Select Employee </option>
            <option value="122" >John Lennon</option>
            <option value="120" >Paul McCartney</option>
            <option value="121" >George Harrison</option>
            <option value="123" >Ringo Starr</option>
            </select></td>
            <td><input type="text" name="frontdesk" id="frontdesk1" size="8"/></td>
            <td><input type="text" name="assistant" id="assistant1" size="8"/></td>
            <td><input type="text" name="sick" id="sick1" size="8"/></td>
            <td><input type="text" name="vacation" id="vacation1" size="8"/></td>
            <td><input type="text" name="other" id="other1" size="8"/></td>
            <td><div class="total" id="total1"></div></td>
        </tr>
    </table>
</form>
</body>
</html>

Open in new window

0
 
nachtmskAuthor Commented:
I recently had to use jquery to do an auto-complete on a form with a database lookup.
It took me the better part of an afternoon to get it working, even with help from EE, but now that I know how to do it, I'll use it whenver I have a chance. It's a nice slick thing to do on a web page that people have become very used to seeing.
I do like the terseness of jquery -- that is once I understand what it's doing.  That cross browser Ajax code is really slick.
0
 
leakim971PluritechnicianCommented:
I don't usually propose to go to jQuery until seeing something like lines 22 to 66 WITH an Ajax call.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.