so i am using jQuery in a crud system where there is an input for quantity that multiplies the price stored in the database and then outputs it in the field next to it but it is outputting it in all the fields next to the input i tried everything but i am unable to do it, any one who can tell me whats wrong with my code,
heres the real output
and this is the result i want
this is my view file
<?php
$i=1;
?>
#foreach ($productData as $rsproductData)
<tr>
<td><?php echo $i ?></td>
<?php
$i++;
?>
<td class="d-none">{{$rsproductData->id}}</td>
<td>{{$rsproductData->products}}</td>
<td>{{$rsproductData->wholesale}}</td>
<td>{{$rsproductData->price}}</td>
<td><input type="number" class="form-control qtyChckInput mb-2" name="qty"></td>
<td class="totalPrice" name="totalPrice">0</td>
<td><button class="btn btn-success editModalBtn">Edit</button></td>
<td><button class="btn btn-danger deleteModalBtn">Delete</button></td>
</tr>
#endforeach
<tfoot>
<tr>
<td></td><td></td><td></td><td></td>
<th>Item Total</th>
<td id="itemTotal">0</td>
<td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<th>10% discount on Item Total</th>
<td id="itemDiscount">0</td>
<td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<th>5% Tax on Item Total</th>
<td id="itemTax">0</td>
<td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<th>Grand Total</th>
<td id="itemGrand">0</td>
<td></td><td></td>
</tr>
</tfoot>
</tbody>
this is my js file
$('input[name*="qty"]').keyup(function()
{
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function () {
return $(this).text();
}).get();
text = $(this).val();
$(".totalPrice").html(data[4] * text)
var itemTotal = $('.totalPrice').html();
$('#itemTotal').html(itemTotal);
var itemDiscount = itemTotal * (1 - 10 / 100);
$('#itemDiscount').html(itemTotal - itemDiscount);
var itemTax = itemTotal * (1 - 5 / 100);
$('#itemTax').html(itemTotal - itemTax);
var itemGrand = itemTax + itemDiscount - itemTotal;
console.log(itemGrand);
$('#itemGrand').html(itemGrand);
});
Try using dynamic id/class for your HTML entities, below is a short calculation for your reference.
<tr>
<td id="products_{{ $rsproductData->id }}">{{$rsproductData->products}}</td>
<td id="wholesale_{{ $rsproductData->id }}">{{$rsproductData->wholesale}}</td>
<td id="price_{{ $rsproductData->id }}" value="{{$rsproductData->price}}">{{$rsproductData->price}}</td>
<td><input type="number" class="form-control qtyChckInput mb-2" data-product="{{ $rsproductData->product }}" name="qty"></td>
</tr>
<script>
$('input[name*="qty"]').keyup(function()
{
var id = $(this).data('product');
var price = $("#price_"+id).val();
var quantity = $(this).val();
// Short calucalation for example
$('#itemGrand').html(price*quantity);
});
</script>
Related
I have this counter for word occurrence in the textarea. The problem is, I have a lot of items in the table, and so it can be distracting to include the zero results.
So what I'm hoping to achieve is, if the user checks the checkbox, it will not show the zero results anymore (preferably the whole row)..
Please see the code so far:
let textarea = $('#textarea3');
textarea.on('keyup', _ => counting());
function counting() {
var searchText = $('#textarea3').val();
let words = [];
words['1 sample'] = '#one';
words['2 sample'] = '#two';
words['3 sample'] = '#three';
words['4 sample'] = '#four';
words['5 sample'] = '#five';
words['6 sample'] = '#six';
for (const word in words) {
var outputDiv = $(words[word]);
outputDiv.empty();
let count = searchText.split(word).length - 1;
searchText = searchText.replaceAll(word,'');
outputDiv.append('<a>' + count + '</a>');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox">
<label> Don't show zero results</label><br>
<button onclick="counting();">Count</button>
<table>
<thead>
<tr>
<th scope="col">Items</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 sample</td>
<td><a id="one"></a></td>
</tr>
<tr>
<td>2 sample</td>
<td><a id="two"></a></td>
</tr>
<tr>
<td>3 sample</td>
<td><a id="three"></a></td>
</tr>
<tr>
<td>4 sample</td>
<td><a id="four"></a></td>
</tr>
<tr>
<td>5 sample</td>
<td><a id="five"></a></td>
</tr>
<tr>
<td>6 sample</td>
<td><a id="six"></a></td>
</tr>
</tbody>
</table>
<textarea id="textarea3" rows="5">
1 sample
2 sample
3 sample
5 sample
</textarea>
If the checkbox isn't checked, it should function as is and still show all results.
I've seen this post but I'm not really sure how to implement it to my own project. Show or hide table row if checkbox is checked
Thank you in advance for any help.
Consider the following.
$(function() {
var textarea = $('#textarea3');
var words = [];
$("table tbody tr").each(function(i, row) {
words.push({
term: $("td:eq(0)", row).text().trim(),
rel: "#" + $("a", row).attr("id"),
count: 0
});
});
function count() {
var searchText = textarea.val();
$.each(words, function(i, word) {
if (searchText.indexOf(word.term) >= 0) {
var re = new RegExp('(' + word.term + ')', 'gi');
word.count = searchText.match(re).length;
$(word.rel).html(word.count);
} else {
word.count = 0;
if (!$("#noShowZero").is(":checked")) {
$(word.rel).html(word.count);
} else {
$(word.rel).html("");
}
}
});
}
textarea.keyup(count);
$("#count-btn, #noShowZero").click(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="noShowZero" type="checkbox">
<label> Don't show zero results</label><br>
<button id="count-btn">Count</button>
<table>
<thead>
<tr>
<th scope="col">Items</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 sample</td>
<td>
<a id="one"></a>
</td>
</tr>
<tr>
<td>2 sample</td>
<td>
<a id="two"></a>
</td>
</tr>
<tr>
<td>3 sample</td>
<td>
<a id="three"></a>
</td>
</tr>
<tr>
<td>4 sample</td>
<td>
<a id="four"></a>
</td>
</tr>
<tr>
<td>5 sample</td>
<td>
<a id="five"></a>
</td>
</tr>
<tr>
<td>6 sample</td>
<td>
<a id="six"></a>
</td>
</tr>
</tbody>
</table>
<textarea id="textarea3" rows="5">
1 sample
2 sample
3 sample
5 sample
</textarea>
When the User:
Enters text in the textbox
Clicks the checkbox
Clicks the Button
then count function is executed.
Count will review all the words and look for specific keywords. A count of them is also retained, as well as element relationship to show that count.
Using Regular Expressions, we can search for the words in the text and count them using .match(). It returns an Array of the matches. You could also use .replace(), to remove them.
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 8 months ago.
I have a table with 4 columns. The first one is the name of a product, the second has the price per item, the third column has an input field where you can choose how many items you want, and the last column calculates the price per item * number of items.
This calculation works, but I also want to calculate all of these into a total at the bottom of the table.
I know very little javascript, so I'm not sure if I'm using the correct functions or methods.
The code consists of PHP, HTML and Javascript.
for ($i = 0; $i < $num_rows; $i++){
echo '<tr><td>' . $row[$i][0] . '';
echo '<td id="stkPris_' . $i . '">' . $row[$i][1] . '</td>';
echo '<td><input type="text" id="antall_' . $i .'" name="antall" size="1" value="0" oninput="calculate(value, this.id)"></td>';
echo '<td><input type="text" id="pris_' . $i . '" name="pris" size="1" readonly></td></tr>';
}
echo '
<tr>
<td><strong>Sum</strong></td>
<td></td>
<td></td>
<td><strong><input type="text" id= "sum" name="sum" size="1" value="0" readonly><strong></td>
</tr>
</table>';
<script>
function calculate(value, elementId){
var i;
for (i = 0; i < ' . $num_rows . '; i++){
var stkPris = document.getElementById("stkPris_" + i);
var antall = document.getElementById("antall_" + i);
var pris = document.getElementById("pris_" + i);
var sum = document.getElementById("sum");
var delsummer = antall.value * stkPris.innerText;
if(elementId == "antall_" + i){
pris.value = delsummer;
}
sum.value += pris.value;
}
}
</script>
How it looks (image)
The total seem to be a string and not a number? I have tried putting the "price per item" into an input instead and use .value instead of .innerText. Didn't do anything.
Here is a simple way to calculate stock and price, read code comments to know more.
$(document).ready(function(){
var totalStock = 0;
var totalPrice = 0;
$(".stock").each(function(){
var s = parseInt($(this).text()); // to get the stock count
var p = parseFloat($(this).parent().find(".price").text()); // to get unit price of this stock
$(this).parent().find(".sumPrice").html(s*p); // calculate Stock x Price
totalStock += s; // calculate total Stocks
});
$(".price").each(function(){
var p = parseFloat($(this).text()); // to get unit price
totalPrice += p; // calculate total prices
});
$(".stockTotal").html(totalStock); // show total stock count
$(".priceTotal").html(totalPrice); // show total prices
$(".generalTotal").html(totalStock * totalPrice); // calculate all prices x all stock
});
table{
width:100%;
}
table th, table td{
border:1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>Stock</th>
<th>Price</th>
<th>Sum</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>item name</td>
<td class="stock">25</td>
<td class="price">17</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>2</td>
<td>item name</td>
<td class="stock">1</td>
<td class="price">12.5</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>3</td>
<td>item name</td>
<td class="stock">6</td>
<td class="price">9.75</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>4</td>
<td>item name</td>
<td class="stock">0</td>
<td class="price">20</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>5</td>
<td>item name</td>
<td class="stock">11</td>
<td class="price">15</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>6</td>
<td>item name</td>
<td class="stock">3</td>
<td class="price">3.25</td>
<td class="sumPrice">##</td>
<tr>
</tbody>
<tfoot>
<tr>
<td colspan="2"></td>
<td class="stockTotal">#stock total#</td>
<td class="priceTotal">#price total#</td>
<td class="generalTotal">#price total x stock total#</td>
</tr>
</tfoot>
</table>
I have a problem here that when I click copy row and I want to get the remaining qty per item, the result is not accurate.
So let's just say the item mouse has 100 qty, and I inputted new qty for 50. So the remaining should be 50. And when I copied the item mouse and inputted 40, so the remaining now is 10. Same goes for other items. This should be the expected output.
Current Situation
JSFIDDLE
$('.qty').on("keyup", function() {
var id = $(this).data('id');
var value = $(this).val();
var sum = 0;
$("#table_name .qty").filter(function(){
if ($(this).data("id") == id){
sum += parseFloat(value);
}
});
console.log(sum);
$('.remaining').val(sum);
});
Your overall logic is REALLY unclear. Here is an example that might help.
$(function() {
function refreshIndex($t) {
$('tbody tr', $t).each(function(i, el) {
var c = i + 1;
var select = $(this).find('td:eq(0)').text(c);
});
}
function copyRow(e) {
var self = $(e.target);
var row = self.closest("tr");
row.clone().appendTo(self.closest("tbody"));
refreshIndex($("#table_name"));
}
function updateItem(e) {
var self = $(e.target);
var row = self.closest("tr");
var p = parseInt(self.val());
var q = parseInt(row.find("td:eq(2) input").val());
$('.remaining', row).val(q - p);
}
$("#table_name tbody").on("keyup", '.price', updateItem);
$("#table_name tbody").on('click', '.copy', copyRow);
});
#table_name tr td input {
width: 4em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Total</th>
<th>Qnty</th>
<th>Action</th>
<th>Remaing</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><input type="text" value="100" readonly></td>
<td><input type="text" class="price" data-id="79"></td>
<td><button class="copy" id="copy-1">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><input type="text" value="20" readonly></td>
<td><input type="text" class="price" data-id="80"></td>
<td><button class="copy" id="copy-2">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><input type="text" value="50" readonly></td>
<td><input type="text" class="price" data-id="81"></td>
<td><button class="copy" id="copy-3">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
</tbody>
</table>
When I enter 40 under Price, 60 appears as the difference between the Quantity and the Amount entered.
When Copy is clicked, a new row is appended, and functionality is binded to it already due to use of .on().
Hope that helps.
Basically you can use the data-id attribute to target the rows you actually want to update.
var clone_controll = function(num) {
//Needed to mod this so add rows have the event handler
$('#table_name').on("keyup", ".qty", function() {
var id = $(this).data('id');
var value = $(this).val();
var sum = 0;
//Filter is the wrong choice here - it is designed to filter objects
/*$("#table_name .qty").filter(function(){
if ($(this).data("id") == id){
//I think this logic is incorrect as well
//You are only getting the value from the
//field you are typing in
sum += parseFloat(value);
}
});*/
/*Use a better selector with each()*/
$("#table_name [data-id=" + id +"]").each(function(){
//In this context "this" is the item iterated in "each"
sum += parseFloat($(this).val());
console.log(sum);
});
console.log("Final: " + sum);
//Here is your problem, this updates All "remaining fields
//$('.remaining').val(sum);
//All rows contiaining this data id
var relevantRows = $("[data-id=" + id + "]").closest("tr");
//Update the "remaining fields in those rows
$(relevantRows).find(".remaining").val(sum);
});
}
clone_controll();
var $tableBody = $('#table_name').find("tbody");
clickEvent();
function clickEvent(){
$tableBody.find('.copy').off('click').on('click',function() {
$trLast = $(this).closest('tr'),
$trNew = $trLast.clone();
$trLast.after($trNew);
clickEvent();
clone_controll();
});
function refresh_index(){
$('#table_name > tbody > tr').each(function (i) {
i++;
var select = $(this).find('td').eq(0).text(i);
});
}
refresh_index();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Qty</th>
<th>Your Qty</th>
<th>Action</th>
<th>Remaing per item(not per row)</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><input type="text" value="100" readonly></td>
<td><input type="text" class="qty" data-id="79"></td>
<td><button class="copy" id="copy-1">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><input type="text" value="20" readonly></td>
<td><input type="text" class="qty" data-id="80"></td>
<td><button class="copy" id="copy-2">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><input type="text" value="50" readonly></td>
<td><input type="text" class="qty" data-id="81"></td>
<td><button class="copy" id="copy-3">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
</tbody>
</table>
Your logic is still pretty unclear, but hopefully this gets you moving in the right direction.
i want to get the value of Save using jquery through input on keyup function.. i am matching value with Buy..means if value matched with the value(range) of Buy..then get the value of Save..
for example if i entered 3 in textfield then it gets value from Save 45%..and if i entered 8 then result should be 51%..entered 15 result 56% and so on.
here is image link for better understanding.
http://easycaptures.com/fs/uploaded/807/3129634990.jpg
<table class="attribute_table">
<tbody>
<tr>
<th>Buy</th>
<th>Unit</th>
<th>Price/unit</th>
<th class="save_red">Save</th>
</tr>
<tr>
<td>3-5</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.99</span></td>
<td class="save_red">45%</td>
</tr>
<tr>
<td>6-11</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.49</span></td>
<td class="save_red">51%</td>
</tr>
<tr>
<td>12-23</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.99</span></td>
<td class="save_red">56%</td>
</tr>
<tr>
<td>24+</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.90</span></td>
<td class="save_red">57%</td>
</tr>
</tbody>
</table>
here is input field
<label for="">Enter Quantity</label>
<input type="text" name="qty" id="qty"></input>
i have tried some code but still no luck..
Try adding data attributes holding the price limits on each td contains the price limits:
$(document).on('input', '#qty', function() {
var that = $(this);
var val = that.val();
if (!isNaN(val)) {
$('.limitTd').each(function() {
var thatTd = $(this);
//var from = parseInt(thatTd.attr('data-from'));
//var to = parseInt(thatTd.attr('data-to'));
var lim = thatTd.html().toString().split('-');
if (lim.indexOf('-') != -1) {
var from = parseInt(lim[0]);
var to = parseInt(lim[1]);
} else {
var from = parseInt(lim.toString().replace('+'));
var to = 9999999;
}
console.log(lim);
if ((val >= from) && (val <= to)) {
var save = thatTd.closest('tr').find('.save_red').html();
$('#saveDiv').html(save);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="attribute_table">
<tbody>
<tr>
<th>Buy</th>
<th>Unit</th>
<th>Price/unit</th>
<th class="save_red">Save</th>
</tr>
<tr>
<td class="limitTd" data-from="3" data-to="5">3-5</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.99</span></td>
<td class="save_red">45%</td>
</tr>
<tr>
<td class="limitTd" data-from="6" data-to="11">6-11</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.49</span></td>
<td class="save_red">51%</td>
</tr>
<tr>
<td class="limitTd" data-from="12" data-to="23">12-23</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.99</span></td>
<td class="save_red">56%</td>
</tr>
<tr>
<td class="limitTd" data-from="24" data-to="99999">24+</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.90</span></td>
<td class="save_red">57%</td>
</tr>
</tbody>
</table>
<label for="">Enter Quantity</label>
<input type="text" name="qty" id="qty"></input>
<div id="saveDiv" style="border:1px solid #d8d8d8;width: 100px;height:50px;float:left"></div>
ALTERNATIVE (No data attributes)
If you don't want to use data attributes, you must manipulate the html to extract the price limits.
For example:
var lim = $('.limitTd').html().split('-');
var from = lim[0];
var to = lim[1];
var mapUnits = [];
$('tr').each(function(i) {
if (!$(this).find("td:nth-child(1)")[0]) {
return;
}
var units = $(this).find("td:nth-child(1)")[0].innerText;
var saveperc = $(this).find("td:nth-child(4)")[0].innerText;
var splits = units.split('-');
var range1 = parseInt(splits[0]);
var range2 = parseInt(splits[1] ? splits[1] : 10000);
mapUnits.push({
range1: range1,
range2: range2,
saveperc: saveperc
})
});
$("#qty").keyup(function() {
$('#saveperc').html('');
var val = $("#qty").val();
for (var m in mapUnits) {
if (mapUnits[m].range1 <= val && mapUnits[m].range2 >= val) {
$('#saveperc').html(mapUnits[m].saveperc);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="attribute_table">
<tbody>
<tr>
<th>Buy</th>
<th>Unit</th>
<th>Price/unit</th>
<th class="save_red">Save</th>
</tr>
<tr>
<td>3-5</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.99</span>
</td>
<td class="save_red">45%</td>
</tr>
<tr>
<td>6-11</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.49</span>
</td>
<td class="save_red">51%</td>
</tr>
<tr>
<td>12-23</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.99</span>
</td>
<td class="save_red">56%</td>
</tr>
<tr>
<td>24+</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.90</span>
</td>
<td class="save_red">57%</td>
</tr>
</tbody>
</table>
<label for="">Enter Quantity</label>
<input type="number" name="qty" id="qty"></input>
<div id='saveperc'></div>
If you cant change the Html, do like this.
Try with -
$('#qty').on('keyup', function() {
var trs = $('table.attribute_table').find('tr:not(:first)');
var val = trs.find('td:first').text();
values = val.split('-');
if ($(this).val() >= values[0] && $(this).val() <= values[1]) {
var dis = trs.find('td.save_red').text();
alert(dis);
}
})
I'm not excellent with javascript as you will see by the code (http://jsfiddle.net/au59P/2/). I've got my calculations partially working, but with a lot of incorrect results. I've spent all night working on it so I need some pointers to see where I'm going wrong.
Here's the HTML:
<table cell-spacing="0" cell-padding="0">
<tbody>
<tr>
<td>Int</td>
<td>40.00</td>
<td>
<input />
</td>
<td>30.00</td>
<td></td>
</tr>
<tr>
<td>Int</td>
<td>50.00</td>
<td>
<input />
</td>
<td>30.00</td>
<td></td>
</tr>
<tr>
<td>Int</td>
<td>60.00</td>
<td>
<input />
</td>
<td>30.00</td>
<td></td>
</tr>
<tr>
<td colspan="3"></td>
<td>Subtotal</td>
<td class="subtotal"></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Int</td>
<td>40.00</td>
<td>
<input />
</td>
<td>40.50</td>
<td></td>
</tr>
<tr>
<td>Int></td>
<td>50.00</td>
<td>
<input />
</td>
<td>45.50</td>
<td></td>
</tr>
<tr>
<td>Int</td>
<td>60.00</td>
<td>
<input />
</td>
<td>50.50</td>
<td></td>
</tr>
<tr>
<td colspan="3"></td>
<td>Subtotal</td>
<td class="subtotal"></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Int</td>
<td>40.00</td>
<td>
<input />
</td>
<td>30.00</td>
<td></td>
</tr>
<tr>
<td>Int></td>
<td>50.00</td>
<td>
<input />
</td>
<td>40.00</td>
<td></td>
</tr>
<tr>
<td>Int</td>
<td>60.00</td>
<td>
<input />
</td>
<td>50.50</td>
<td></td>
</tr>
<tr>
<td colspan="3"></td>
<td>Subtotal</td>
<td class="subtotal"></td>
</tr>
</tbody>
<tr>
<td class="active">Active</td>
<td class="total"></td>
<td colspan="3"></td>
</tr>
</table>
Here's the js:
var sumVal = 0;
function currentSum(){
$(".subtotal").each(function(){
sumVal += parseFloat($(this).text()).toFixed(2);
});
};
$("input").keyup(function(){
var newRate = parseFloat($(this).val(), 10).toFixed(2);
var multiplier = parseFloat($(this).parent().next("td").text(), 10).toFixed(2);
var calcRate = parseFloat(newRate * multiplier).toFixed(2);
$(this).parent().next("td").next("td").text("$" + calcRate).addClass("calculated");
var $tr = $(this).closest("tbody").find("tr");
var $total = $tr.has("td[colspan]");
var subCalc = 0;
$tr.not($total).each(function(){
if($(this).find(".calculated").text() !== ""){
var tempCalc = parseFloat($(".calculated").text().replace("$",""),10).toFixed(2);
subCalc += +parseFloat(tempCalc).toFixed(2);
};
});
$total.find("td.subtotal").text("$" + subCalc);
currentSum();
$(".active").next(".total").text(sumVal);
});
When entering a value in the input, it updates the multiplier in the 5th td, however the subtotal calculation is wrong, and the total calculation returns NaN. What's more, when I delete the value in one of the inputs, everything turns to NaN where I thought I had that if conditional in there to ignore all NaN.
Few problems
function currentSum() {
var sumVal = 0;
$(".subtotal").each(function () {
sumVal += parseFloat($(this).text().replace('$', '')) || 0;
});
return sumVal.toFixed(2);
};
then
$(".active").next(".total").text('$' + currentSum());
Demo: Fiddle
You need to check that parseFloat returns you a correct number before using it:
var someVar = /* parseFloat ... */
if (!isNaN(someVar)) {
// use someVar
}
Your main problem being parseFloat("$10") gives NaN because of the $
Updated fiddle (there are still some issues with computations)
var sumVal = 0;
var subCalc = 0;
function currentSum(){
$(".calculated").each(function(){
sumVal = (parseFloat(sumVal)+parseFloat($(".calculated").text().replace("$",""),10)).toFixed(2);
});
};
$("input").keyup(function(){
var newRate = parseFloat($(this).val(), 10).toFixed(2);
var multiplier = parseFloat($(this).parent().next("td").text(), 10).toFixed(2);
var calcRate = parseFloat(newRate * multiplier).toFixed(2);
$(this).parent().next("td").next("td").text("$" + calcRate).addClass("calculated");
var $tr = $(this).closest("tbody").find("tr");
var $total = $tr.has("td[colspan]");
$tr.not($total).each(function(){
if($(this).find(".calculated").text() !== ""){
var tempCalc = parseFloat($(".calculated").text().replace("$",""),10).toFixed(2);
subCalc = parseFloat(parseFloat(subCalc)+parseFloat(tempCalc)).toFixed(2);
};
});
$total.find("td.subtotal").text("$" + subCalc);
currentSum();
$(".active").next(".total").text(sumVal);
});
I made some changes to your script. It solves some problem. You can proceed from there.