Multiply form td by input - javascript

I have a form, with a table inside.
Each row 4 columns:
Item Name
Item Price (this is set by me, not user)
Quantity (set by user input)
Total (price*qty)
I want it to reflect totals live.
JSFiddle:
http://jsfiddle.net/uyyzkLny/
Code Snippet:
<tr class="txtMult">
<td>Salmon</td>
<td class="val1" type="number">28</td>
<td><input name="Fish1" class="val2" size="2px"/></td>
<td><span class="multTotal">0.00</span></td>
</tr>
--
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
});
Issue:
Keep getting 0. (or NaN). From what I know about Jquery, the issue is that I'm treating val1 as user input instead of hard-coded. How do I fix that? Is that the problem?
TIA

You can't use .val on a td, so you need to get the .text() of the element, and parse it as an integer (optional, but a good idea):
var $val1 = parseInt($('.val1', this).text())
http://jsfiddle.net/uyyzkLny/2/

Here's a fiddle that will give you a start - just a different approach - FIDDLE.
Key points:
uses HTML limiters to keep number to an integer between 0 and 10
'$' is stripped off for the calculation and then put back for the total.
JS
$('input[type=number]').change( function(){
$('.mytable tr td:nth-child(2)').each( function(index, element){
var price = $(this).text().slice(1);
var number = $(this).closest('td').next('td').find('input').val();
var total = (price * number).toFixed(2);
$(this).closest('td').next('td').next('td').text('$' + total );
console.log(price + ' *** ' + number + ' *** ' + total);
});
});

Use
$('.val1', this).text()
instead of
$('.val1', this).val();
Updated fiddle here

Related

How to calculate subtotal and total and show the result using jquery

I have a purshase form with two items.
the first item which is a number box who identify how many adults in the trip.
the second item which is a number box who identify how many seniors in the trip.
for example :
I want when I select 2 in the first number box, the subtotal next to the number box show me the result of the calculation ( price of one person * 2)
also for seniors section.
I found a code which is work with select and option value :
update_amounts();
$('select').change(update_amounts);
function update_amounts() {
var sum = 0.0;
$('#tickets > tbody > tr').each(function () {
var qty = $(this).find('option:selected').val();
var price = $(this).find('.price').text().replace(/[^\d.]/, '');
var amount = (qty * price);
sum += amount;
$(this).find('.subtotal').text('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + amount);
});
$('#total').val('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + sum);
};
I have edited this code to my needs like this :
$('input').change(update_amounts);
function update_amounts() {
var sum = 0.0;
$('#tickets > tbody > tr').each(function () {
var qty1 = $(this).find('#adults').val();
var qty2 = $(this).find('#senior').val();
var price = $(this).find('.price').text().replace(/[^\d.]/, '');
var amount = ((qty1+qty2) * price);
sum += amount;
$(this).find('.subtotal').text('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + amount);
});
$('#total').val('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + sum);
};
But it doesn't work!
this is the Html code :
<input type="number" name="adult_count" id="adults" min="0" required>
<input type="number" name="senior_count" id="seniors" min="0" required>
this image shows what I need :
https://i.ibb.co/52qzkh7/stack2.png

balancing two input number fields in jquery

I would like to balance two input number fields using jquery based on the max value set for both. for example its like a balance, if one side goes down the other goes up and vice versa. another example if the max value is 20 then if i enter 5 in input field one then 15 would be left in input field two.
Need the help Thanks. Haven't started coding it as yet stuck trying to figure it out.
First you need to attach the input eventhandler on all of the relevant input fields. This event handler will compare the current input value of a input fields to the total/max value variable and find the remainder accordingly. The event handler then finds the other input fields and assigns them with the appropriate remainder values.
Note: This allows you to add as many inputs as you want and it will
balance them all out. Just remember to add the balance class on the
input field.
var total = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
this.value = value = 0;
} else if (value > total) {
this.value = value = total;
}/* else if (value < 0) {
this.value = value = 0;
}
* Remove this comment if value shouldn't be negative.
*/
var remainder = total - value;
var otherInputs = $('.balance');
otherInputs.splice($.inArray(this,otherInputs),1);
var remainderDiv = remainder/otherInputs.length;
$.each(otherInputs, function(input) {
otherInputs[input].value = remainderDiv;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
Update: The two inputs can be less than the max but never higher.
var max = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
value = 0;
}
var otherInputs = $('.balance');
var sum = 0;
$.each(otherInputs, function(input) {
sum += parseInt(otherInputs[input].value);
});
if (sum > max)
this.value = max - (sum - value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
here's a fiddle to get you started (and maybe finished):
https://jsfiddle.net/ahmadabdul3/xwyrrw53/1/
html:
<input type='number' id='first' class='balancable'/>
<input type='number' id='second' class='balancable'/>
js:
$(function() {
var max = 20;
var balanceOpposite = {
'first': 'second',
'second': 'first',
}
$('.balancable').on('input', function() {
var id = $(this).attr('id');
var thisVal = $(this).val();
$('#' + balanceOpposite[id]).val(20 - thisVal);
});
});

Add a class if var < 0 jquery

I do not know what I am doing wrong. For some reason I can not add this class to the #total-weight with JS. The CSS is fine because I have hard coded and is working. The sum is working perfect as well.
/********** This is my HTML **************/
<tr id="results">
<td>Grade (%)</td>
<td><input type="text" value="" id="final-grade" name="final-grade"></td>
<td><input type="text" value="100" id="total-weight" name="total-weight"><span><small> remaining (%)</small></span></td>
</tr>
/******** This is my JS ***************/
'use strict';
$(document).on('keyup', '.weight-value', function() {
// the sum of weight (%)
var sumWeight = 0;
var totalWeight = 0;
$('.weight-value').each(function(){
sumWeight += +$(this).val();
});// end of sum of weight (%)
// populate weigth remaining
totalWeight = $('#total-weight').val(100 - sumWeight);
if(totalWeight < 0) {
$('#total-weight').addClass('table-border');
}
});// end document .on keyup
$('#total-weight').val(100 - sumWeight) will set the value of the element and return a jQuery object. So your condition will not work.
Also you might want to use toggleClass(), since you want to remove the class if the value is >=0
'use strict';
$(document).on('keyup', '.weight-value', function () {
// the sum of weight (%)
var sumWeight = 0;
var totalWeight = 0;
$('.weight-value').each(function () {
sumWeight += +$(this).val();
}); // end of sum of weight (%)
// populate weigth remaining
totalWeight = 100 - sumWeight;
$('#total-weight').val(totalWeight);
$('#total-weight').toggleClass('table-border', totalWeight < 0);
}); // end document .on keyup
Demo: Fiddle

JQuery Set Odd, Even of Total

I have a table that sum Columns and Rows, and shows the result of the sum.
I have to change the color of each total. If is even, put it "green". If it is odd put it "red"
This is my table:
<table id="sum_table">
<tr>
<td><input value="0" class="sum1" /></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr>
<td><input value="0" class="sum1"/></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr>
<td><input value="0" class="sum1"/></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr class ="totalCol">
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<button id="tabla">+</button>
JQuery:
//Sumamos las columnas
$(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
total += parseInt(this.value);
});
$table.find('.totalCol td:nth-child('+thisNumber+')').html(total);
});
//AƱadimos filas y coumnas cuando se clica al boton "+".
$("#tabla").click(function () {
$("#sum_table tr:last-child").before("<tr>"+$("#sum_table tr:eq(0)").html()+"</tr>");
$("tr:not(:last-child)").each(function () {
var classname = $(this).find("td:last-child").index() + 1;
$(this).find("td:last-child").before('<td><input class="sum' + classname + '" type="text" value="0"></td>');
});
$("#sum_table tr:last-child").append("<td>0</td>");
});
//Creamos la funcion newSum para hacer la suma y mostrarlo en el total.
$(document).on('keyup','input',newSum);
function newSum() {
var sum = 0;
var thisRow = $(this).closest('tr');
var total = 0;
$(thisRow).find("td:not(.total) input").each(function () {
sum += parseInt(this.value);
});
$(thisRow).find(".total").html(sum);
$('.total').each(function () {
total += parseInt($(this).html());
});
}
DEMO JSFIDDLE
Try this, put this code below in newSum() function
if ((this.value % 2 == 0)) {
$(this).css('color', 'green');
} else {
$(this).css('color', 'red');
}
DEMO
I have updated your fiddle please check.
$(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
total += parseInt(this.value);
});
var total_field = $table.find('.totalCol td:nth-child('+thisNumber+')');
total_field.html(total);
if(total % 2 == true) {
total_field.css("background","red");
}
else {
total_field.css("background","green");
}
});
try this way
JQUERY CODE:
if (total % 2 == 0)
$table.find('.totalCol td:nth-child(' + thisNumber + ')').css('color', 'green'); //set green to even total
else
$table.find('.totalCol td:nth-child(' + thisNumber + ')').css('color', 'red'); //set red to odd total
LIVE DEMO:
http://jsfiddle.net/hdhZZ/7/
Happy Coding :)
Each time one of the inputs is changed, check to see if the total value is an odd or even number...
This is rough, I would toggle a class rather than edit the inline css..
$('td input').on('change', function(){
$('.totalCol td').each(function(){
var $total = parseInt($(this).html());
if ($total !==0 && $total % 2 === 0) {
$(this).css('background-color','green');
}
else {
$(this).css('background-color','#fff');
}
});
});
I realise you've already accepted an answer, but I'd suggest rewriting your approach to the following (though the colouring approach is the same as suggested by the the other answers):
function sumTotals(){
// caching variables:
var table = $('#sum_table'),
inputRows = table.find('tr:not(.totalCol)'),
inputCells = inputRows.find('td:not(.total)');
// iterating over each of the 'td' elements in the '.totalCol' row:
$('.totalCol td').each(function(i,e){
/* i is the index of the current element over which we're iterating
among the collection returned by the selector,
e is the element (the 'this'), which we're not using here.
We're using ':nth-child()' to look at the 'input' elements from
each column, and creating an array of the values using 'map()'
and 'get()': */
var sum = inputRows.find('td:nth-child(' + (i + 1) + ') input').map(function(){
return parseFloat(this.value) || 0;
}).get().reduce(function (prev, curr) {
/* 'reduce()' allows us to perform a calculation (summation) of the
values in the returned array: */
return prev + curr;
});
// setting the text of the current 'td' to the sum,
// using CSS to set the color to either green (even) or red (odd):
$(this).text(sum).css('color', sum % 2 === 0 ? 'green' : 'red');
});
/* iterating over each of the rows with inputs, finding the
last 'td', and updating its text: */
inputRows.find('td:last-child').text(function(){
// caching:
var $this = $(this),
/* getting all the previous 'td' elements, and their 'input'
descendant elements, mapping their values: */
sum = $this.prevAll('td').find('input').map(function(){
return parseFloat(this.value) || 0;
}).get().reduce(function (prev, curr) {
return prev + curr;
});
// setting the color (as above):
$this.css('color', sum % 2 === 0 ? 'green' : 'red');
return sum;
});
}
$('#sum_table').on('keyup change input paste', 'tr:not(.totalCol) input', sumTotals);
JS Fiddle demo.
References:
CSS:
:last-child.
:nth-child().
JavaScript:
Array.prototype.reduce().
parseFloat().
jQuery:
css().
find().
get().
map().
on().
prevAll().
text().

Jquery Calculating

I running a similar script to this script from fiddle
http://jsfiddle.net/QmTNZ/2/
I tried to modify it to work with my table.
Here is the link to the table on the product page
http://styleso1.nextmp.net/dev/shop/safari-pu-sleeve-jacket.html
I need it to calculate the Qty ( input box, Column 4) X the unit price ( Column 5 ) and show the sum in column 6
How would i modify the JS to do this?
Here is what i have for the JS
$(function(){
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td").eq(1);
console.log($qnt + " | " + $price);
var sum = parseFloat($price.text()) * parseFloat($qnt.val());
$(this).find(".a-center1").text(sum);
$overall += sum;
});
$("#total").text($overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup',function(){ca();});
});
Any Help would be very appreciated
Try this
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td:eq(4)").find('.price');
console.log($qnt + " | " + $price);
var pri = $price.text();
pri = pri.replace('$', '');
var sum = parseFloat(pri) * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' + sum);
$overall += sum;
});
$("#total").text('$' +$overall);
Check Fiddle
You can save some DOM searching and text parsing by doing some simple things like adding the unit price as a data attribute to the row and retrieving it with jQuery data() method
HTML
<tr class="sum" data-unit_price="10.00">
JS
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $row=$(this);
var $qnt = $(this).find(".qty");
var cost = $row.data('unit_price');
var sum = cost * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' +sum);
$overall += sum;
});
$("#total").text('$' +$overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});
DEMO: http://jsfiddle.net/Jk976/3/

Categories