Using jQuery to sum values from a couple text inputs - javascript

I have a couple of text inputs and I would like to compute the sum of the values in another input. This must happen on the fly, as soon as the user enters a value in one of the inputs. I'm planning to use jQuery for this, and I would like to add a class name for each input, something like class="input1", class="input2" and so on.
My problem is that I don't know to add all those values, and given the fact that I have over 50 inputs, I don't want to "add them by hand".
Any kind of help is appreciated.

If you decorate all of the inputs you want added together with classes of input1, input2, and so on, this will get the sum of the current values in all those inputs
var sum = 0;
$("input[class *= 'input']").each(function(){
sum += +$(this).val();
});
Then naturally if you want to put this value in an input of id destination
$("#destination").val(sum);
Here's a fiddle
EDIT
If you want this to run whenever any of these textboxes are changed, then you can put this in a change event handler
$(document).on("change", "input[class *= 'input']", function() {
var sum = 0;
$("input[class *= 'input']").each(function(){
sum += +$(this).val();
});
$("#destination").val(sum);
});
Here's that fiddle
EDIT
Per Jaspers comment, if you know that input1, input2, etc, will always be the first class on your inputs, ie, you'll never do
<input class='someNewClass input1'
then you could
$("input[class ^= 'input']").each(function(){
^= means starts with, while *= means contains anywhere.

give them a common name and you need to parse the value since it will be text initially
var result= 0;
$("input[name='sum']").each(function(){
result = result + parseInt($(this).val(),10);
});

Related

set attributes of elements stored in variables

Is there anyway to use jQuery to dynamically set the attributes of HTML elements that are stored in variables?
For example, at one point in my application, a user creates a varying number of select input fields. For eventual processing by PHP, the elements need to be named in the format name='input'+siteNumber+'['+x+']', where x is the number of elements created in a for loop.
Here's a rough sketch of what I'm thinking needs to be done - THIS IS NOT FUNCTIONAL CODE, IT IS ONLY AN ILLUSTRATION.
$(".number_select").change(function(){
numberFound = $(this).val();
siteNumber = $(this).parent().attr('data-site_number');
//HERE'S THE INPUT TO BE NAMED
selectInput = "<select></select>";
this['inputArray' + siteNumber] = [];
for(x = 1; x <= numberFound; x++){
//THIS IS WHAT I'D LIKE TO ACCOMPLISH - SETTING THE ATTRIBUTE - THOUGH THIS UNDERSTANDABLY DOES NOT WORK IN THIS PARTICULAR FORMAT
this['inputArray' + siteNumber].push(selectInput.attr("name", "species"+siteNumber+"["+x+"]"));
};
$(this).parent().append(this['inputArray' + siteNumber]);
};
Thank you.
Thanks everyone - I actually ended up deciding to handle this a little differently, but it works perfectly - rather than storing the elements in variables, I used a function instead...
function inputs(siteNumber, x){
return ("<select name='selectInput"+siteNumber+"["+x+"]'>"+list+"</select>");
};
$(".number_select").change(function(){
numberFound = $(this).val();
siteNumber = $(this).parent().attr('data-site_number');
this['inputArray' + siteNumber] = [];
for(x = 1; x <= numberFound; x++){
this['inputArray' + siteNumber].push(inputs(siteNumber, x));
};
$(this).parent().append(this['inputArray' + siteNumber]);
};
Don't know why I didn't think of this in the first place, it seems obvious to me now. Oh well, live and learn.
To vaguely answer your question, you can dynamically generate an element and use jQuery's attr for adjusting the name attribute pretty easily like so.
var select = $('<select>').attr('name', 'add-name-here');
$('<option>').attr('value', 'some-value').text('Option').appendTo(select);
$('#wrapper').html(select);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper"></div>
Which outputs
<select name="add-name-here">
<option value="some-value">Option</option>
</select>
In your case, instead of adding it to #wrapper you would build up the select box as you need and append it to whichever select box has the change? Not sure your specific use case. Hope it 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

javascript running total adding incorrectly

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);
}

Calculating the total of an online order form using javascript

I'm working on a basic order form and I would like to see if I can build it from stratch.
I have a form which is made up of a table with 12 items listed and text input fields for item quantity. What I would like to do is have the code run through the form to check for any quantities that have been entered, then relate these values to the prices in an array.
So far I have the array:
var juicePrice = new Array();
juicePrice["citrusZing"]=20.00;
juicePrice["strawberrySmooth"]=22.00;
juicePrice["carrotSpin"]=21.50;
juicePrice["Tropical"]=20.75;
...
and a way to run through the form:
calculateTotal()
{
var juiceForm = document.forms["juiceform"];
//Get a reference to the juice the user Chooses name=selectedJuiceQty":
var selectedJuiceQty = juiceForm.elements["selectedJuiceQty"];
for(var i = 0; i < selectedJuiceQty.length; i++);
but I'm not quite sure how to connect the information from the form to calculate the totals. Can anyone point me in the right direction? Is it something like this?
for(var i = 0; i < selectedJuiceQty.length; i++){
var juiceTotal = 0;
if(selectedJuiceQty[i]>0) {
juiceTotal += juicePrice[selectedJuiceQty[i].value]*selectedJuiceQty;
//If we get a match then we break out of this loop
break;
}
return total;
}
Is it possible to use the same name tag for each field or should I just use citrusZingQty = parseInt(document.getElementById("citrusZing").value); for each item? Then I would have to list all of the items, which doesn't seem a very elegant way. What would happen if multiple items are selected?
Any help anyone can give to point me in the right direction would be great.
So you can do what you want. Michael pointed this out in the comments but it may have been overlooked.
var myPrices = new Object();
myPrices['eggs'] = 1.50;
myPrices['bread'] = 1.00;
// ...
Then you can loop through your form fields and check against your 'myPrices' object.
EDIT
To answer your question in the comments - I would not use the same name for all of my input fields. It does make looping through the form easier perhaps. However, using the id/class of the input tag is not a nice solution in my opinion. HTML id/class are there for CSS/Javascript manipulation and using it to identify which fruit the input represents will not be apparent to other developers working on the project (I realize this may be a small project for you but it's best not to start any bad habits). I would name each input after the juice/drink it represents.

Find the sum of all values of spinners with same class

I have a group of spinners <select> input fields and I want to find the sum of them live. I figured the easiest way would be to use jquery's class selector but it does not store the .val()'s of elements of a similar class in an array.
Is there a way to store all the values of a bunch of <select> Inputs in an array so I can find the sum of all of their values.
My not working code looks like this.
function calcPrice() {
var price = $('.food').val() || [];
}
$("select").change(calcPrice);
This might be overkill, but you could use http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm
or you could simply do:
var price = 0.0
$(".food'").each(function() {
price += +this.value
});
Would you mind to clarify what are the .food elements? Are they input fields? Otherwise, you may want to try using $('.food').text() instead.
Similar to btiernay's answer, but if you wanted to keep the actual array you can do:
var prices = $.map($(".food"), function () {
return +this.value;
});
var expenses = 0.0;
$(".expense").each(function() {
expenses += +this.value;
});
$("#expense-total").html(expenses);
Basically the same as btiernay but it has missing ; which could fool noobs. Also added jquery element example to push the final value to a sum field. Sorry I could't add as a comment as I rarely post so reputattion less than 50.
Live example under business expeses here: http://contractor.icalculator.info/calculator/PAYE-calculator.html

Categories