Solved

Adding numbers in javascript/Ajax

Posted on 2013-11-26
22
226 Views
Last Modified: 2013-12-05
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
0
Comment
Question by:nachtmsk
  • 8
  • 8
  • 3
  • +1
22 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 39677744
please post HTML for a row
0
 

Author Comment

by:nachtmsk
ID: 39677779
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
 
LVL 14

Accepted Solution

by:
Pierre Cornelius earned 250 total points
ID: 39677838
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
 

Author Comment

by:nachtmsk
ID: 39677881
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
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 250 total points
ID: 39677923
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
 
LVL 14

Expert Comment

by:Pierre Cornelius
ID: 39677933
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
 
LVL 14

Expert Comment

by:Pierre Cornelius
ID: 39677937
@leakim
from the code he posted, it does not look like he is using JQuery
0
 

Author Comment

by:nachtmsk
ID: 39677945
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
 
LVL 15

Expert Comment

by:VincentPuglia
ID: 39678032
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
 

Author Comment

by:nachtmsk
ID: 39678120
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
 
LVL 15

Expert Comment

by:VincentPuglia
ID: 39678190
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 82

Expert Comment

by:leakim971
ID: 39678279
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
 

Author Comment

by:nachtmsk
ID: 39678329
I should get into jquery. Just don't have the time to learn something new it seems.
Thanks
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39678353
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
 
LVL 15

Expert Comment

by:VincentPuglia
ID: 39678362
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
 

Author Comment

by:nachtmsk
ID: 39678371
LeaKim -- wow, didn't realize it was that simple.  When you show the example next to regular Javascript it makes perfect sense. Cool.
0
 

Author Comment

by:nachtmsk
ID: 39678384
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
 
LVL 82

Expert Comment

by:leakim971
ID: 39678401
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
 
LVL 82

Expert Comment

by:leakim971
ID: 39678411
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
 
LVL 82

Expert Comment

by:leakim971
ID: 39678443
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
 

Author Comment

by:nachtmsk
ID: 39678486
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
 
LVL 82

Expert Comment

by:leakim971
ID: 39678536
I don't usually propose to go to jQuery until seeing something like lines 22 to 66 WITH an Ajax call.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now