Solved

autmatically add input values as entered

Posted on 2013-02-04
10
204 Views
Last Modified: 2013-02-05
I'm creating a deposit form

I just completed getting it setup to add a new row.  Now I'd like it to auto-sum the input fields.  I won't know a set number of how many fields there will be as the user can add rows as necessary.

Another hiccup is that I am using another function in the field to auto populate a dollar sign as well as the comma and period necessary to confirm the amount.
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	  num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	if (num =="0") {
		return(" ");
	} else {
	return (((sign)?'':'-') + '$' + num + '.' + cents);
	}
  }

Open in new window


Here is the code I found to add the fields, but it only does it when a button is clicked.  It also can't handle the function formatCurrency() as shown above.
$(function() {
            $("#btn1").click(function() {
                var add = 0;
                $(".test").each(function() {
                    add += Number($(this).val());
                });
                $("#para").text("Sum of all textboxes is : $" + add);
            });
        }); 

Open in new window


any suggestions?
0
Comment
Question by:axessJosh
  • 5
  • 4
10 Comments
 
LVL 9

Accepted Solution

by:
WebDevEM earned 500 total points
Comment Utility
Hi,

I've made a quick jsFiddle that should be what you're looking for... http://jsfiddle.net/webdevem/4jrr4/

I hope this helps!

WebDevEM
0
 
LVL 9

Expert Comment

by:WebDevEM
Comment Utility
Oh, and if you're allowing new rows to be created after the page is loaded you may want to look at either .on() or .live() depending on which version of jQuery you're using.  Otherwise the new <input> boxes won't trigger your tally formula.  Or you can un-bind and re-bind the click function every time a new input is created but that's not the smoothest way.  (Still works, though!)
0
 
LVL 2

Author Comment

by:axessJosh
Comment Utility
works great, Thanks.

Just realized one piece that I'd like to adjust that I didn't mention in the question.

I'd like to total to tally in an input box labeled "total deposit" so that I can INSERT that into a table for deposits.  Can you show me how to adjust?
0
 
LVL 9

Expert Comment

by:Sar1973
Comment Utility
In JS it could be document.getElementById("DepositSum").value=(Total);
where DepositSum is the ID of your labeled input.
0
 
LVL 9

Assisted Solution

by:WebDevEM
WebDevEM earned 500 total points
Comment Utility
Yep, that would work in pure JS.  The jQuery version would be
 $("#DepositSum").val(add);

Open in new window

(I've updated the jsFiddle as well, if you want to tinker with it)
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 2

Author Comment

by:axessJosh
Comment Utility
Awesome!  works great.

I made a slight addition to the jQuery to format the number into currency.

$("#DepositSum").val(formatCurrency(add));

Open in new window


Only thing that I cannot get to work now is the formatCurrency on the input fields.  I need this to be sure the user gets the decimal point in the correct place.

its currently:
<input type="text"  value="" name="lineAmount[]" class="test" id="lineAmount" onChange="formatCurrency(this)"></input>

Open in new window

0
 
LVL 9

Assisted Solution

by:WebDevEM
WebDevEM earned 500 total points
Comment Utility
Okay... that one took a little playing with to get what I think you're looking for.  (Plus jsFiddle is very slow for me today for some reason)

I've updated the fiddle at http://jsfiddle.net/webdevem/4jrr4/ to format the text box as you leave it, and remove the $ and , when you enter, leaving just numbers and decimal points to edit.  Those are the blur and focus sections of code.
0
 
LVL 2

Author Comment

by:axessJosh
Comment Utility
that helps for the inputs, i did change the code a bit to get the inputs as their class, rather than just general input.

Here's the issue now.

when i enter on the first line, it sums fine, however when i tab off that field, it removes the sum total in the box.

when i add a row, then enter a value it works fine, but doesn't validate the number.  The sum still works though.
0
 
LVL 9

Expert Comment

by:WebDevEM
Comment Utility
Can you post your html and javascript code, or share the URL to the page if it's visible to the outside world?  It sounds like you just missed a reference when you changed the code to look at the classes, since it was working before that.  (I'm assuming my jsFiddle works as you wanted it, and the problem is with your copy.  If mine doesn't work for you, we can look at that too)

First place I'd look is in the blur and focus lines.  Oh, which reminds me... did you copy the new function "formatNumber(myStr)" ?
0
 
LVL 2

Author Closing Comment

by:axessJosh
Comment Utility
overlooked the new function added at the top of the JSFiddle file.

Great piece of code.  Thanks!
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
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…

763 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

16 Experts available now in Live!

Get 1:1 Help Now