multiplying values - javascript

Im using the following method to add up text boxes. I have tried changing multiple things and cant seem to multiply two text box values! essential I want 2 text box that values are multiplied and displayed in a third text box. I want this value to be fluid aka change when the number changes! I was using this code because i may be multiplying more then one thing but if this is too much of a hassle i will live with just multiplying two at a time
The code im using to add is
<!--adding script #-->
<script>
$(document).ready(function(){
calculateSum();
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$("#sum").val(sum.toFixed(2));
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
var total = document.getElementById("subtotal").value == "";
var total = document.getElementById("subtotal").value = sum;
}
<!--END adding script #-->
I tried setting the last line to
var times1 = document.getElementById(subtotal);
var times2 = document.getElementById(tax);
var equal = times1.value * times2.value;
and then changing var total1 = document.getElementById("total1").value = sum9; to var total1 = document.getElementById("total1").value = equal;
The text boxes id are subtotal and tax the box im trying to update is total1.
Thanks alot!

On every keyup, instead of getting all values and adding them explicitly, it is better to deduct the previous value of the corresponding input and add the current updated value to sum..
Also, if subtotal is correctly calculated, then the multipication operation what ever you have done should work correctly..
Please find the following jsfiddle where the sum is calculated as explained above along with multiplying the tax..
http://jsfiddle.net/tgvrs_santhosh/77uxK/1/
Let me know if you still face the issue..

Instead of this
if(!isNaN(this.value) && this.value.length!=0) {
I think a regular expression may work better because you are using string values
if (/^([-]?((\d+)|(\d+\.\d+)|(\.\d+)))$/.test(this.value)) {
I haven't tested this regex, but you should be able to find a good regex to test for valid numbers if this one doesn't work for some reason. Also I noticed you have a == after that getElementById.
I'm not totally certain it matters, but you can do sum += (this.value * 1) instead of parseFloat.
update
Try this var equal = ($("#subtotal").val() * 1) * ($("#tax").val() * 1);

I found your question very confusing, but I think what you're trying to say is you want to add up all the .txt fields to get a sub-total, then multiply that sub-total by a tax rate to get a total. If so, then you already know the sub-total is a valid number due to the way you calculate it, so then:
var tax = +$("#tax").val(), // get tax and convert to a number
total = tax ? sum * tax : sum; // if tax is a non-zero number multiply
// otherwise just take the sum as is
If your tax field is not an input then use .text() instead of .val().
Your existing code is rather more complicated than it needs to be. You can do this:
$(document).ready(function(){
calculateSum();
// you don't need an .each() loop, you can bind a keyup handler
// to all elements in the jQuery object in one step, and you don't
// need the anonymous function since it does nothing but call calculateSum:
$(".txt").keyup(calculateSum);
});
function calculateSum() {
var sum = 0,
val;
//iterate through each textboxes and add the values
$(".txt").each(function() {
// you don't need to test for NaN: just attempt to convert this.value
// to a number with the unary plus operator and if the result is not
// a number the expression val = +this.value will be falsy
if(val = +this.value)
sum += val;
});
$("#sum").html(sum.toFixed(2));
var tax = +$("#tax").val();
$("#total1").html((tax ? sum * tax : sum).toFixed(2));
}
For some reason the unary plus operator used throughout my answer is not widely known, but I prefer it to parseFloat().

Related

Calculate Quantity * Price = Total | Total / Price = Quantity

I need some help.
I want the "Total" to be calculated by the "quantity * price = total" (so far it's ok). The problem is that I also need "Quantity" to be calculated by "total / price = quantity" ie if one field is changed the other will automatically change.
I made a very simple example code: JSFiddle
//Value of Price (Hidden)
$('#price').val(31245);
//Calculation
var qty=$("#qty");
qty.keyup(function(){
var total=isNaN(parseInt(qty.val()* $("#price").val())) ? 0 :(qty.val()* $("#price").val())
$("#total").val(total);
});
var total=$("#total");
total.keyup(function(){
var qty=isNaN(parseInt(total.val()/ $("#price").val())) ? 0 :(total.val()/ $("#price").val())
$("#qty").val(qty);
});
//Mask Total input
var originalVal = $.fn.val;
$.fn.val = function(value) {
if (typeof value == 'undefined') {
return originalVal.call(this);
} else {
setTimeout(function() {
this.trigger('mask.maskMoney');
}.bind(this), 100);
return originalVal.call(this, value);
}
};
$('#total').maskMoney();
$('#total').on('click mousedown mouseup focus blur keydown change input', function(event) {
console.log('This Happened:'+ event.type);
});
In it the first part "quantity * price = total" works ok and is updated automatically. However, when in the second part "total / price = quantity" is the problem appears.
When the number entered in the Total input is too large (Example: 9,876.23) the quantity is not calculated automatically and returns 0. But if the number is for example 893.23 the quantity works as it should.
Could any of you help me? (sorry for my bad english)
Ps: I needed the value of the quantity field not to exceed 8 decimals (example: 0.00000000). But in all the attempts I had the calculation does not work.
The easiest way to debug this is to breakpoint the appropriate spot and see what's happening. For instance, in Chrome, pull up your Dev Tools, find the result panel, and set a breakpoint:
Then, in the console, start evaluating parts of the expression. Here, I've evaluated total.val(). So what's happening?
The key thing to realize is that total.val() returns a string! So what happens when you use something like "9,873.76" as a number? That's right, JavaScript doesn't know what to do with the comma and punts, returning NaN.
Why did it show up when you had a number in the thousands? Because smaller numbers don't have commas.
So, as a result, you're getting zero.
The thousands separator made automatically by the mask is not understood in the calculation, so you should remove it first from the input
var qty=isNaN(parseInt(total.val().replace(",", "")/ $("#price").val())) ? 0 :(total.val().replace(",", "")/ $("#price").val())
however, the problem will appear if more than one thousands separator appears (1,000,000), so you you can globally remove all thousands separators:
var my_total = total.val().replace(/,/, "");

Calling total from an array, multiply by a number and display a result

Please review this Fiddle...
I have some select menus where if you select some college credit amounts, it computes a running total and displays it under the selects. (Thanks #barbara-laird)
I'm trying to take the total and multiply it by a number (561) and then display a result. The result is set not to exceed 40,392.
This is the JS to calc the value I'm looking for...
$('#total_Credits select').change(function () {
var sum = 0;
$('#total_Credits select').each(function (idx, elm) {
sum += parseFloat(elm.value, 10) * 561;
});
$('#total_money').html(Math.min(sum, 40392).toFixed(2))
calcTotals();
});
...but it's not calculating the value. It's pulling from a valid ID.
I'm not sure why, but it's not displaying anything.

jquery event is not working properly

i have a Invoice form and a jquery function.
In Invoice if i enter the quantity greater then the available quantity then i have to alert the user.
My problem is: Let the max quantity is 5, if i input data as 7 (single digit>max avail quantity) then my code is working fine. But if i enter two digigist number eg. 17(two digists>max avail quantity) then my alert box is not coming.
I mean onkeyup my function is working only with single digit.
How can i make it happening? Please help.
$('input[name="quantity"]').keyup(function()
{
//problem is here
var $tr = $(this).closest("tr");
var unitprice = $tr.find('input[name^="unitprice"]').val();
var q = $tr.find('input[name^="quantity"]').val();
var cq = $tr.find('input[name^="checkquantity"]').val();
if(q>cq)
{
alert("Error: Quantity value exceeds then available quantity..Max Quantity is "+cq);
//this works fine only if single digit is entered in textbox quantity
}
//----below are some other stuffs -these are working fine
$tr.find('input[name^="sprice"]').val($(this).val() * unitprice);
var totalPrice = 0;
$('input[name="sprice"]').each(function()
{
totalPrice += parseFloat(this.value);
$('[name=subtotal]').val(totalPrice);
});
});
--------------
------------
// Form containing the above textboxes
<input type="submit" id="submitbtnId" value="Save"/>`
q > cq is comparing 2 strings, which is not what you want. You're trying to compare the numerical value of those strings.
Use this instead:
if ( +q > +cq)
{
// alert your error
}
Note that by prefixing the variables with the + sign, you're converting them to a number.
Better yet, convert them to a number as soon as you get the values:
var $tr = $(this).closest("tr");
var unitprice = +$tr.find('input[name^="unitprice"]').val();
var q = +$tr.find('input[name^="quantity"]').val();
var cq = +$tr.find('input[name^="checkquantity"]').val();
if ( q > cq )
{
alert("Error: Quantity value exceeds then available quantity..Max Quantity is " + cq);
}
You need to use parseInt() to ensure you are comparing integers, not strings:
if (parseInt(q, 10) > parseInt(cq, 10)) {
/* Rest of your code */
}
Your values are compared as string. If you want to compare Numbers, either use:
parseInt() or parseFloat()
or
[..].val() * 1, but this will return 'NaN' if its no digit, while parseInt() and parseFloat() will return 0

Total Price variable limit to 2 decimals using ajax with php

I am using the following code snippet to calculate a total price. This works great except #totalPrice on some occasions expands out to for example $267.9999999999. How do I reformat #totalPrice within this function to just round to two decimals as is standard in dealing with price.
function getTotalCost(inventory) {
if(inventory) {
getTotalParts(inventory);
getTotalMarkup(inventory);
}
var labor = $('#labor').val() * 1;
var totals = 0;
for(i in totalMarkup) {
totals += totalMarkup[i];
}
totalCost = totals+labor;
/*if(totals == 0) {
totalCost = 0;
}*/
$('#totalPrice').html(totalCost);
}
You can have:
$('#totalPrice').html(totalCost.toFixed(2));
See:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
Notice that toFixed method returns a formatted number, therefore converts the number to a string. It's not a problem here because html wants a string, but it's keep it in mind that in order to avoid concatenation of string when you expects sum of numbers. I believe you use $('#labor').val() * 1; for this very reason. However it's not necessary, it's better use method like parseFloat or the unary plus operator:
var labor = +$('#labor').val();
When working with javascript the floating points are always a bad. Best you can do is, round it up.
But in this case you can do
(totalCost).toFixed(2);
You can use Math.round function in JavaScript like this.
totalCost = Math.round(totalCost*100)/100;
$('#totalPrice').html(totalCost);

If # is present, calculate the total, if all #s are not calculated, let the total still be calculated

as you can see in the picture, it would be silly for the user to have to type in all 5 Requested Brands (as that is not required). Maybe they only want to choose one Requested Brand. As it is currently set up, the subtotal is only calculated if the user enters 5 unit costs and 5 quantities...not good. If they don't enter all 5, subtotal returns NaN.
$("a#full_sub_total").click(function(event){
event.preventDefault();
var first = $("div#total_result").text();
var second = $("div#total_result1").text();
var third = $("div#total_result2").text();
var fourth = $("div#total_result3").text();
var fifth = $("div#total_result4").text();
$("#full_total_results p").text((parseInt(first,10) + parseInt(second,10) + parseInt(third,10) + parseInt(fourth,10) + parseInt(fifth,10)));
});
Any help is greatly appreciated.
I would loop over the total_result fields, and incrementally add their parsed values to a total var:
$("a#full_sub_total").on("click", function(){
var total = 0;
$("div[id^=total_result]").text(function(i,t){
total += parseInt( t, 10 ) || 0;
});
$(".full_total").text("$" + total);
});
Note the main part of all of this:
total += parseInt( t, 10 ) || 0;
When the attempt to parse an integer from the text of the element fails, we return 0 in its place. This will not offset the total value, and will permit us to continue along with out any NaN showing up later.
Demo: http://jsbin.com/axowew/2/edit
Basic technique:
var sum = 0;
var num1 = parseInt(text1, 10);
if (!isNaN(num1)) sum += num1;
// ...
(Loops: even better idea.)
The problem your overall total results in NaN is that anytime one or more of individual line total is empty, it will cause your overall result total to equal NaN in your attempt to add (i.e. #+#=#, #+NaN=Nan)
Simplify solution to your problem:
$('#subtotal').click(function(e) {
e.preventDefault();
// Clear overall total
$('#overallTotal').empty();
// Loop through each line total
$('div.lineTotal').each(function() {
// If line total is not empty, add
if ($(this).text() != ''){
$('#overallTotal').text(parseInt($('#overallTotal').text) += parseInt($(this).text()));
}
});
});

Categories