javascript running total adding incorrectly - javascript

Hey everyone I'm trying to do a very simple calculation using javascript to find a running total. I seem to be missing something. I did look through SO and found some very similar scenarios but, I can't seem to relate to my own code.
Here is the script I am using to calc my running total.
var total = 0;
function GetTotal(txtBox) {
total += parseInt(txtBox.value) || 0;
$("#chkTotal").html(total);
}
and here is some code from my view:
<div class="editor-field">
#Html.TextBox("FirstDemo", String.Empty, new { id = "firstdemo", onchange = "GetTotal(this)" })
#Html.ValidationMessageFor(model => model.FirstDemo)
</div>
<div>
<h3>Total Checked</h3>
</div>
<div id="chkTotal"></div>
The total calculates perfectly, until a value is changed in a text box, in which case whatever has been entered in the textbox is added again to the running total.
Can anyone help me?

The problem is the global scope of your total variable: I imagine you have several text fields in the form where you set them up to handle the onchage event the same way. The first time you enter something, the value is added correctly to total but the moment you change something in any of the text fields, it adds again the new value. Again, because total has global scope.
You should really move total locally inside the function and re-parse all values in the input elements you are interested in.
Since you are using jquery, you could do something like this instead:
function GetTotal(txtBox) {
var total = 0;
$('input:text').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}​
Here's a jsfiddle demonstrating it for you.

Easiest solution, loop through all the form elements and redo the calculation.
I see jQuery in your code so it is a basic selector that gets the elements and an each loop.
function GetTotal(txtBox) {
var total = 0;
$(".calculationClass").each(
function() {
total += parseInt(this.value,10) || 0;
}
);
$("#chkTotal").html(total);
}

Related

How do increment value while it being declared inside function

I have a small issue where i'm trying to increment/decrement the buttons in x steps this is all dynamic dependant on what ever the quantity step is, my code works fine when its increments of one because i am just using ++ there is no scope issue
I've tried a few things but no much luck i can't really declare it outside of the function as there is multiple input boxes and i'd need to do some sort of mapping to know which one relates to which input.
I know what the issue is its because of scoping im defining a variable inside a function but its not a simple thing to do it outside of it any other solutions to get past this without defining it outside ?
When i had it like this this.$refs[codeForRef][0].value++ it worked fine and would increment by one
increment: function(e) {
e.preventDefault();
var codeForRef = e.srcElement.id;
var test = parseInt(this.$refs[codeForRef][0].value, 10); //the value of the qty
test += this.dyQty //whatever it needs to go up in
},
what i understood from your question, this should work for you.
increment: function(e) {
e.preventDefault();
var codeForRef = e.srcElement.id;
var test = parseInt(this.$refs[codeForRef][0].value, 10); //the value of the qty
test += this.dyQty //whatever it needs to go up in
this.$refs[codeForRef][0].value = test;
}

Problems with onclick / calculating a sum

Let me start by saying, that while I have some programming experiencing (some basic C from a college class and I once wrote a FORTRAN programm in college for a professor), I am utterly new to JS and beginning to get a bit frustrated.
For some reason, even after reading tutorials and watching several YouTube videos on objects, I seem unable to wrap my head around it. I understand the fundamentals and have no problems doing very basic stuff, like writing a loop that prints out increments on a HTML site, but every time I try something practical, I am completely at a loss.
Here is my current problem: I have created this HTML site that generates a shopping list. Basically, when I click on one of the buttons next to an item name, it adds that item to the list in the middle of my screen. Thanks to Google I found a piece of JavaScript code which, through try and error, I managed to tweak for this purpose:
<!-- click this button to add the item-->
<button onclick="myFunction('ITEM1', 100)" class="sidebarbuttons" >ITEM1 </button>
/* Create a List one line at a time- */
<script>
function myFunction( x, y ) {
var node = document.createElement("LI" );
var textnode = document.createTextNode(x);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script>
So far, so good. Now I want to get the net price for all the items. Which means, When I click the button, I want a function to add the price of that item to a variable and then display that variable in a field with
document.getElementById("result").innerHTML = total_sum;
Here's my question: how, oh my god, how do I do this? I thought I could add the following:
function myfunction(x,y){
var sum = 0;
var sum+=y;
}
document.getElementById("result").innerHTML = 'sum';
Obviously, this doesn't work at all. Can you please give me some hints what I have to do to make this work?
First of all,
please consider to study JavaScript better, because it's a falsy easy programming language and it's very dangerous to copy&paste without knowing the language. It's quite normal to read a lot, watch a lot and don't know where to start, and it's the main reason because people hates JavaScript: because we don't know well JavaScript. So consider to read the book series "You Don't Know" by Kyle Simpson.
About your question. You can add a variable to storage the sum of your items and when you click to an item, you can add to it:
var total_sum = 0;
function myFunction( x, y ) {
var node = document.createElement("LI" );
var textnode = document.createTextNode(x);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
showResults(y);
}
function showResults(price){
total_sum += parseFloat(price)
document.getElementById("result").innerHTML = total_sum;
}
JSBIN
Let me know ;)
So you are on the right track. Picking up where you left off in your last code block, there are few things you will need to change.
//declare the variable outside of the function... otherwise it will only be available to you within that function.
var totalSum = 0;
// then within your function you will be able to successfully add to the global totalSum variable
function calculateSum(x){
totalSum += x;
// and lastly... set the innerHTML within the function... which should equal the variable totalSum
document.getElementById("result").innerHTML = totalSum;
}
Hope this helps.

Automatic updating of calculation result in jQuery

I'm making my first steps in js and jquery and I'm trying to make simple calculation form,
which
takes numeric variable form form in html (sum)
multiplies it by constat multiplier
multiplies result by a number choosen from dropdown list (total)
and does that on the fly, so to say updates result whenever any variable changes.
code below works, but total result does not update when sum updates. what am I missing here?
$('.pow').keyup(function () {
var sum = 0;
var multip = 4;
sum1 = sum;
$('.pow').each(function() {
sum += Number($(this).val())*parseInt(multip);
sum1 = sum;
});
$("#sum").html(sum.toFixed(2)); });
$('.per').click(function () {
var total = 0;
var period = $("#period").val();
$(".per").each(function() {
total = parseInt(sum1)*parseInt(period);
}); $("#sum1").html(total.toFixed(2)); });
working fiddle here
You calculate totals on ( $('.per').click(.....);, so when you type a number above, nothing happens, because the code does not run)
The easier way to do this would be to automate a click after typing a number.
Add this $('.okr').click(); after this line here $("#sum").html(sum.toFixed(2));
Like so:
$("#sum").html(sum.toFixed(2));
$('.per').click();
Assuming you already chose from the dropdown it will be fine, otherwise the dropdown wont have a value to calculate with.
Also, the problem with the dropdown is AS soon as I click it closes, i.e. I cant choose anything. To solve this issue I hold the mouse button down, so the dropdown wont close (this is not normal). The reason is because you do dropdown.click() { dropdown.change() } think about replacing this functinality

jquery getting value from input

This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.

dojo foreach function

I am quite new to dojo and I'm stuck with a problem here
I have a zend dojo form where I need to take sum of four elements and set the value to another element. I have assigned a class (score) to those four elements
".score" : {
"found" : function (ele) {
var widgetId = ele.getAttribute('widgetid');
dojo.connect(dijit.byId(widgetId),'onBlur', function(){
var sum = 0;
dojo.query('.score')
.forEach(function(ele){
var widgetId = ele.getAttribute('widgetid');
sum += parseInt(dijit.byId(widgetId).get('value'));
});
//***cannot get the value of sum here
dijit.byId('score_total').set('value', sum);
});
}
}
As commented I am unable to get the sum of those values outside the foreach. Is there any way to get the value out of the loop? Am I doing any thing wrong?
It seems that I had made a mistake in the code and since I am quite new to jscript I was unable to debug. foreach indeed is not a asynchronous and sum was being calculated just that the parseInt(dijit.byId(widgetId).get('value')) was returning not a number NaN hence I was unable to populate the form element, I simply added an if condition and it worked
if(parseInt(dijit.byId(widgetId).get('value'))){
sum = sum + parseInt(dijit.byId(widgetId).get('value'));
}
Sorry for the trouble
One thing to note... dojo.foreach is deprecated ...
http://livedocs.dojotoolkit.org/dojo/forEach
instead ... array.forEach
http://livedocs.dojotoolkit.org/dojo/_base/array#forEach
but i think you might also have a scoping issue as well.. try something like this..
var sum = 0;
var elements = dojo.query('.score');
array.forEach(elements, function(ele) {
var widgetId = ele.getAttribute('widgetid');
sum += parseInt(dijit.byId(widgetId).get('value'));
});
in your case, the parent context has the variable, so it will work as you have used it.
Just a side point that if you want to access the sum variable outside the parent context, you will need to use dojo.hitch or pass the context to dojo.forEach
http://www.ibm.com/developerworks/web/library/wa-aj-dojo/
see the section on "Setting method context"

Categories