Calculate summation from data in input fields by using javascript - javascript

I'm starting at learning javascript and I have a problem
here is my html code:
<tr>
<td>
Qty1 : <input class="txt" type="number" id="qty1"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id1"></td>
</tr>
<tr>
<td>
Qty2 : <input class="txt" type="number" id="qty2"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id2"></td>
</tr>
<tr>
<td>
Qty3 : <input class="txt" type="number" name="qty" id="qty3"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id3"></td>
</tr>
<br><br>
<tr>
<td>Summation of value : </td>
<td><span id="sums">0</span></td>
</tr>
and here is my js code
/* get data */
qty1.oninput = function() {
var inputF1 = document.getElementById("id1");
inputF1.value = qty1.value*2;
};
qty2.oninput = function() {
var inputF2 = document.getElementById("id2");
inputF2.value = qty2.value*3;
};
qty3.oninput = function() {
var inputF3 = document.getElementById("id3");
inputF3.value = qty3.value;
};
/* calculate sumation */
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".getPrice").each(function() {
$(this).on('input',function(){
calculateSum();
});
});
calculateSum();
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".getPrice").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
$("#sums").html(sum.toFixed(2));
}
My problem is that when I click on the Qty input fields then the summation should be calculated. However, I have to enter values for the value input fields for my calculate function works.
How I can fix it? My expected result is that when I input the qyt input field it must calculate the summation and return the result.
For example, when I entered 1 in Qty1 field the summation should be 2 then I entered 3 in Qty2 the summation should return 11 and so on.
Thank you for your help!
my demo code: https://jsfiddle.net/1c0r6uhd/

You will have to call calculateSum after each value field is updated. Currently, you call it on the input event, which is fired before the actual value has been updated. Here is an example:
$('#qty1').on('input', function() {
$('#id1').val(this.value * 2).change();
})
$('#qty2').on('input', function() {
$('#id2').val(this.value * 3).change();
});
$('#qty3').on('input', function() {
$('#id3').val(this.value).change();
});
$('.getPrice').change(function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".getPrice").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
$("#sums").html(sum.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>
Qty1 : <input class="txt" type="number" id="qty1"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id1"></td>
</tr>
<tr>
<td>
Qty2 : <input class="txt" type="number" id="qty2"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id2"></td>
</tr>
<tr>
<td>
Qty3 : <input class="txt" type="number" name="qty" id="qty3"/>
</td>
<td>Value: <input type="text" class="getPrice" id="id3"></td>
</tr>
<br><br>
<tr>
<td>Summation of value : </td>
<td><span id="sums">0</span></td>
</tr>
</tbody>
</table>

Related

Need to get the total and discount calculated on a table row via Javascript

I need to calculate totals and the discount amounts on the following table.
<tbody id="generate_invoice_table">
<tr>
<td>16</td>
<td>Glass Polish Normal</td>
<td><input type="text" class="form-control text-right quantity" value="1"></td>
<td class="price">8000.00</td><td><input type="text" class="form-control text-right discount"></td>
<td><input type="text" disabled="" class="form-control text-right amount"></td>
<td><input type="checkbox" checked="" name="check-invoice"></td>
</tr>
</tbody>
So basically, I want to enter quantity and then the discount and show the amount at the last input box.
The Javascript is given below, I get the message trs.find is not a function...
$('#invoice').delegate('.quantity,.price,.discount', 'keyup', function () {
var t = document.getElementById("generate_invoice_table");//find table data
var trs = t.getElementsByTagName("tr");
var qty = trs.find('.quantity').val();
var price = trs.find('.price').val();
var dis = trs.find('.discount').val();
varamt = (qty * price) - (qty * price * dis) / 100;
trs.find('.amount').val(amt);
total();//calculate total and show after the invoice table
});
});
function total() {
var t = 0;
$('.amount').each(function (i, e) {
varamt = $(this).val() - 0;
t += amt;
});
$('.total').html(t);
}
delete line with var t= and try to replace the next line whit this code:
var trs = $("#generate_invoice_table tr");
As was mentioned it's bettter to choso what you gonna use pure JS or jQuery. On example below there are onkeyup events on discount and quantity inputs. In event handler recalc() price, quantity and discount are read using document.getElementById selectors. The amount calculated and inserted into appropriate input.
amt count I took without changes.
function recalc() {
var price = Number(document.getElementById('price').innerText);
var quantity = Number(document.getElementById('quantity').value);
var discount = Number(document.getElementById('discount').value);
var total = '';
if (price && quantity) {
total = discount ? ((quantity * price) - (quantity * price * discount) / 100) : (quantity * price);
}
document.getElementById('amount').value = total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody id="generate_invoice_table">
<tr>
<td>16</td>
<td>Glass Polish Normal</td>
<td>
<input type="text" id="quantity" class="form-control text-right quantity" value="1" onkeyup="recalc()">
</td>
<td class="price">
<span id="price">8000.00</span>
</td>
<td>
<input type="text" id="discount" class="form-control text-right discount" onkeyup="recalc()">
</td>
<td>
<input type="text" disabled="" id="amount" class="form-control text-right amount">
</td>
<td>
<input type="checkbox" checked="" name="check-invoice">
</td>
</tr>
</tbody>
Hope this helps

Why there is a 0 in the start of the value of the last input? [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 6 years ago.
See this code. when I type some numbers in the .price and .qty inputs, if actually the t variable is 100, I get 0100 in the .total input. Why there is a 0 in the first and how can I solve it?
$('.detail').delegate('.quantity, .price, .discount', 'keyup', function() {
var tr = $(this).parent().parent();
var qty = tr.find('.quantity').val();
var price = tr.find('.price').val();
var amt = qty * price;
tr.find('.amount').val(amt);
total();
});
function total() {
var t = 0;
$('.amount').each(function(i, e) {
var amt = $(this).val();
t += amt;
});
$('.total').html(t);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody class="detail">
<tr class="row">
<td>
<input type="text" class="no" value="1">
</td>
<td>
<input type="text" class="pid">
</td>
<td>
<input type="text" class="productname">
</td>
<td>
<input type="text" class="price">
</td>
<td>
<input type="text" class="quantity">
</td>
<td>
<input type="text" class="amount">
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><span class="total"></span></td>
</tr>
</tbody>
</table>
SEE THE FIDDLE: https://jsfiddle.net/z5d421at/
Your amount from the value is being read as a string. Use parseInt().
$('.detail').delegate('.quantity, .price, .discount', 'keyup', function() {
var tr = $(this).parent().parent();
var qty = tr.find('.quantity').val();
var price = tr.find('.price').val();
var amt = qty * price;
tr.find('.amount').val(amt);
total();
});
function total() {
var t = 0;
$('.amount').each(function(i, e) {
var amt = parseInt($(this).val());
t += amt;
});
$('.total').html(t);
}
An elements value is always a string, so $(this).val() returns a string, and doing "0" + "100" returns "0100" as those are strings.
You have coerce the strings to numbers
var t = 0;
$('.amount').each(function(i, e) {
var amt = +$(this).val();
t += amt;
});

HTML Table - Iterate over row and sum the fields

I have then following table:
<table style="width:100%" id="testTable">
<tr>
<th>length per</th>
<th>width per</th>
<th>length</th>
<th>width</th>
<th>total</th>
</tr>
<tr align='right'>
<td>
<input type="text" name="length-per-input">
</td>
<td>
<input type="text" name="width-per-input">
</td>
<td>
<input type="text" name="length-total-input">
</td>
<td>
<input type="text" name="width-total-input">
</td>
<td>
<input type="text" name="total-output" disabled="disabled">
</td>
</tr>
<tr align='right'>
<td>
<input type="text" name="length-per-input">
</td>
<td>
<input type="text" name="width-per-input">
</td>
<td>
<input type="text" name="length-total-input">
</td>
<td>
<input type="text" name="width-total-input">
</td>
<td>
<input type="text" name="total-output" disabled="disabled">
</td>
</tr>
</table>
<input type=button value='+' onclick="addRow()" />
<input type=button value='Calculate' onclick="Calculate()" />
I also have the javascript which adds the value and puts it in total:
<script>
function Calculate() {
var lengthPerInput = $("input[name='length-per-input']").val();
var widthPerInput = $("input[name='width-per-input']").val();
var lengthTotal = $("input[name='length-total-input']").val();
var widthTotal = $("input[name='width-total-input']").val();
var total = (lengthTotal/lengthPerInput) + (widthTotal/widthPerInput);
$("input[name='total-output']").val(total);
}
</script>
The aim here is to have it iterate over the two rows, then add each one separately.
I know how to get each row by using:
$('#testTable tr').each(function(){
console.log(this);
$(this).find('length-per-input').each(function(){
console.log(this);
})
})
But using the row (accessed via "this") I don't know how to get the correct cells, get their value, then perform the calculate on that row for the total.
Any advice on this please? Thank you!
function Calculate(tr_row) {
var lengthPerInput = tr_row.find("input[name='length-per-input']").val();
var widthPerInput = tr_row.find("input[name='width-per-input']").val();
var lengthTotal = tr_row.find("input[name='length-total-input']").val();
var widthTotal = tr_row.find("input[name='width-total-input']").val();
var total = (lengthTotal/lengthPerInput) + (widthTotal/widthPerInput);
tr_row.find("input[name='total-output']").val(total);
}
For every row you call function to summ the values
To the function you pass the row, then it can collect values on that row
$('#testTable tr').each(function(){
Calculate($(this))
})
You can use each() function to iterate through table and use find() function to find cell values.
function Calculate() {
$('#testTable tr').each(function() {
var lengthPerInput = $(this).find("input[name='length-per-input']").val();
var widthPerInput = $(this).find("input[name='width-per-input']").val();
var lengthTotal = $(this).find("input[name='length-total-input']").val();
var widthTotal = $(this).find("input[name='width-total-input']").val();
var total = (lengthTotal/lengthPerInput) + (widthTotal/widthPerInput);
$(this).find("input[name='total-output']").val(total);
});
}
Working Plunker
How to get a table cell value using jQuery?

jquery multiply and divide at the same time

Here are my text fields
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="form_textfield" class="price" autocomplete="off" /></td>
</tr>
<tr>
<td>Liters:</td>
<td><input type="text" name="liters" id="form_textfield" class="liters" autocomplete="off" /></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" name="jqueryamount" id="form_textfield" class="jqueryamount" autocomplete="off" /></td>
</tr>
Currently when you input price and liters, it multiplies them and outputs the answer to jqueryamount textfield it works well. What i want to do is when i type in the amount and the price it will divide the jqueryamount field with the price field and output it to liters field.
UPDATE FIXED
// JavaScript Document
$(document).ready(function(){
$('.price').keyup(calculate);
$('.liters').keyup(calculate);
});
function calculate(e)
{
$('.jqueryamount').val($('.price').val() * $('.liters').val());
}
// JavaScript Document
$(document).ready(function(){
$('.jqueryamount').keyup(calculate1);
$('.price').keyup(calculate1);
});
function calculate1(e)
{
$('.liters').val($('.jqueryamount').val() / $('.price').val());
}
JUST ADDED A NEW NAME FOR THE DIVIDE FUNCTION... silly me thanks for the help guys
Here are my javascript
// JavaScript Document
$(document).ready(function(){
$('.price').keyup(calculate);
$('.liters').keyup(calculate);
});
function calculate(e)
{
$('.jqueryamount').val($('.price').val() * $('.liters').val());
}
// JavaScript Document
$(document).ready(function(){
$('.jqueryamount').keyup(calculate);
$('.price').keyup(calculate);
});
function calculate(e)
{
$('.liters').val($('.jqueryamount').val() / $('.price').val());
}
My problem is when adding the divide function the multiplication part will no longer work, i can no longer type inside the liters textfield it gives me NaN error.
Use parseFloat() function after the get the value from input, which converts string to number.
When you put the value price and amount the liters would show like this.
$('.price').keyup(calculateLiters, calculateAmount);
$('.jqueryamount').keyup(calculateLiters);
$('.liters').keyup(calculateAmount);
function calculateLiters(e) {
price = parseFloat($('.price').val());
amount = parseFloat($('.jqueryamount').val());
if(!isNaN(price) && !isNaN(amount)){
$('.liters').val(amount / price);
}
}
function calculateAmount(e) {
price = parseFloat($('.price').val());
liters = parseFloat($('.liters').val());
if(!isNaN(price) && !isNaN(liters)){
$('.jqueryamount').val(price * liters);
}
}
Demo
I swapped some class names and id's to make code more efficient.
HTML
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="price" class="form_textfield" autocomplete="off" /></td>
</tr>
<tr>
<td>Liters:</td>
<td><input type="text" name="liters" id="liters" class="form_textfield" autocomplete="off" /></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" name="jqueryamount" id="jqueryamount" class="form_textfield" autocomplete="off" /></td>
</tr>
Javascript
// JavaScript Document
$(document).ready(function(){
$('.form_textfield').keyup(calculate);
});
function calculate()
{
$('#jqueryamount').val($('#price').val() * $('#liters').val());
$('#liters').val($('#jqueryamount').val() / $('#price').val());
}
Here is a working demo. http://jsfiddle.net/vnaDK/

Read value of row using jquery

I need to create sum of the values selected, but i have small problem with the jquery bit.
My html table
<TR>
<TD>
<INPUT disabled onchange=updateDetails() value=33441 CHECKED type=checkbox name=invoiceRow dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees for Searches</TD>
<TD>285.00</TD></TR>
<TR>
<TD><INPUT onchange=updateDetails() value=36486 CHECKED type=checkbox name=invoiceRow dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees</TD>
<TD>3213.03</TD></TR>
my javascript is:
where #InvoiceItemsRows is <tbody> tag
function updateDetails() {
$("#InvoiceItemsRows input[type=checkbox][checked]").parent().last().each(
function(index, value) {
alert(value.html());
}
);
}
Javascript, maybe not as fancy as some of the other ones people have posted but it makes sense.
$(document).ready(function() {
$('[name=invoiceRow]').click(function() {
updateDetails();
});
function updateDetails() {
var total = 0;
var currentnum = 0;
$("input:checked").each(
function(index, value) {
currentnum = $(this).val();
currentnum = Number(currentnum);
total = total + currentnum;
});
alert(total);
}
});
HTML
<TR>
<TD>
<INPUT disabled value="33441" CHECKED type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees for Searches</TD>
<TD>285.00</TD></TR>
<TR>
<TD><INPUT value="36486" CHECKED type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees</TD>
<TD>3213.03</TD></TR>
I fixed some of the missing quotes you may want to finish fixing them though.
Try this (you have to close <Input> tags):
function updateDetails() {
var sum = 0;
$("#InvoiceItemsRows input[type=checkbox]:checked").each(
function() {
sum += parseFloat($(this).closest('tr').children('td:eq(2)').text());
}
);
return sum;
}
alert(updateDetails());
You'll have to change:
$("#InvoiceItemsRows input[type=checkbox][checked]")
To:
$("#InvoiceItemsRows input:checked")
That new rule will return all 'checked' elements. Have a look at the documentation of the :checked selector.
Try this:
var total = 0;
$('#InvoiceItemsRows input:checked').each(function() {
total += $(this).val();
});
I suspect you want to total what's in the <td> though?
you have invalid html your your values need quotes
<tr>
<td>
<input disabled="disabled" onchange="updateDetails()" value="33441" checked="checked" type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"> <input type="hidden" name="isProfFee">
</td>
<td>
Professional fees for Searches
</td>
<td>
285.00
</td>
</tr>
<tr>
<td>
<input onchange="updateDetails()" value="36486" checked="checked" type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"> <input type="hidden" name="isProfFee">
</td>
<td>
Professional fees
</td>
<td>
3213.03
</td>
</tr>
and then
$("#InvoiceItemsRows input:checked")

Categories