how to get value from table td using javascript - javascript

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

Related

display correct age depending on date value

I have a table which have a tbody and x number of rows containing persons and their ages like this..
<tbody>
<tr>
<td class="number">4</td>
<td class="name">Name</td>
<td class="age" data-date="2004-11-22 00:00:00">13</td>
</tr>
<tr>
<td class="number">5</td>
<td class="name">Name</td>
<td class="age" data-date="2003-11-22 00:00:00">14</td>
</tr>
I would like to display the correct age of all persons, but since this depends on the current date I'm thinking of entering the birthdate instead. But I still want to display the actual age of the player. How can I use a jQuery script that iterate all rows of the table and depending on the data-date value display the actual age in the corresponding td cell?
$('.age').each(function(i, e) {
var now = new Date();
var date = new Date(e.dataset.date);
$(this).html(now.getFullYear() - date.getFullYear());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="number">4</td>
<td class="name">Name</td>
<td class="age" data-date="2004-11-22 00:00:00"></td>
</tr>
<tr>
<td class="number">5</td>
<td class="name">Name</td>
<td class="age" data-date="2003-11-22 00:00:00"></td>
</tr>
</tbody>
</table>
Maybe something like this:
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
$('.age').each(function(index){
$(this).html(getAge($(this).data('date')));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="number">4</td>
<td class="name">Name</td>
<td class="age" data-date="2004-11-22 00:00:00">13</td>
</tr>
<tr>
<td class="number">5</td>
<td class="name">Name</td>
<td class="age" data-date="2003-11-22 00:00:00">14</td>
</tr>
</tbody>
</table>
the getAge() function is stolen from here: https://stackoverflow.com/a/7091965/2008111 so maybe you follow that link and upvote also the answer there.
Your HTML page should be like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="persons">
<tbody>
<tr>
<td class="number">4</td>
<td class="name">Name</td>
<td class="age" data-date="2004-11-22 00:00:00"></td>
</tr>
<tr>
<td class="number">5</td>
<td class="name">Name</td>
<td class="age" data-date="2003-11-22 00:00:00"></td>
</tr>
</tbody>
</table>
The js side should look like this:
$(document).ready(function(){
$('.persons td.age').each(fucntion(){
var today = new Date();
var birthday = new Date($(this).attr('data-date'));
var ageDifMs = today - birthday.getTime();
var ageDate = new Date(ageDifMs);
$(this).html(Math.abs(ageDate.getUTCFullYear() - 1970));
});
});

Grouping first and last value in array (Consecutive values are group with first and last element)

I have one object array with time intervals , Number 0 indicates sunday . In my time scheduling page selecting different time ranges in a particular day . I want to group the time values . My initial array is given below
time schedule selection looks like
Each cell has data-day and data-time attribute and selected cell with data-selected attribute
i am iterate through the selected time and got the result like
var selectedIntervals = {};
$('td[data-selected]').each(function() {
var a = $(this).attr('data-day');
var b = $(this).attr('data-time');
if(!selectedIntervals[a]) {
selectedIntervals[a]=[];
}
selectedIntervals[a].push(b);
});
I want the output like
{
0: [["00:00", "05:00"],["08:00", "11:00"]]
}
Please help .
Try this:
arr = ["00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "08:00", "09:00", "10:00", "11:00"];
output = [];
start = arr[0];
for(i=1; i<arr.length; i++) {
if(i == arr.length-1) {
output.push([start, arr[i]]);
break;
}
if(parseInt(arr[i]) - parseInt(arr[i-1]) > 1) {
output.push([start, arr[i-1]]);
start = arr[i];
}
}
Here is a function to make intervals from an array of hour strings.
function makeInterval(arr) {
//e.g. arr = ["00:00", "01:00", "02:00", "03:00", "06:00", "10:00", "11:00"]
//returns [["00:00", "03:00"], ["06:00", "06:00"], ["10:00", "11:00"]]
var interval, result = [];
for (var i = 0; i < arr.length; i++) {
var hour = parseInt(arr[i]);
if (!interval || (hour != parseInt(interval[1]) + 1)) { //if first time or the hour jumps
interval = [arr[i], arr[i]]; //create new interval
result.push(interval);
}
else {
interval[1] = arr[i]; //update the end of interval
}
}
return result;
}
you can call it like
makeInterval(selectedIntervals[0]);
do a loop over the day number if necessary.
mid = a.length
mid=parseInt(a.length / 2)
b=[[a[0],a[mid]],[a[mid+1],a[a.length-1]]]
console.info(b)
Combining your initial code with elfan's code You get this:
$(function() {
var list = {};
var day = 0;
list[day] = selectedSchedules(day);
day = 1;
list[day] = selectedSchedules(day);
console.log(list);
function selectedSchedules(day) {
var schedules = [];
var interval, hour;
$('td[data-selected][data-day=' + day + ']').each(function() {
var b = $(this).data('time');
var current = parseInt(b);
if (!interval || (current != parseInt(interval[1]) + 1)) {
interval = [b, b];
schedules.push(interval);
} else {
interval[1] = b;
}
});
return schedules;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td data-day="0" data-time="00:00" data-selected="true">00:00</td>
<td data-day="1" data-time="00:00" data-selected="true">00:00</td>
</tr>
<tr>
<td data-day="0" data-time="01:00" data-selected="true">01:00</td>
<td data-day="1" data-time="01:00" data-selected="true">01:00</td>
</tr>
<tr>
<td data-day="0" data-time="02:00" data-selected="true">02:00</td>
<td data-day="1" data-time="02:00" data-selected="true">02:00</td>
</tr>
<tr>
<td data-day="0" data-time="03:00" data-selected="true">03:00</td>
<td data-day="1" data-time="03:00" data-selected="true">03:00</td>
</tr>
<tr>
<td data-day="0" data-time="04:00" data-selected="true">04:00</td>
<td data-day="1" data-time="04:00" data-selected="true">04:00</td>
</tr>
<tr>
<td data-day="0" data-time="05:00" data-selected="true">05:00</td>
<td data-day="1" data-time="05:00" data-selected="true">05:00</td>
</tr>
<tr>
<td data-day="0" data-time="06:00">06:00</td>
<td data-day="1" data-time="06:00">06:00</td>
</tr>
<tr>
<td data-day="0" data-time="07:00">07:00</td>
<td data-day="1" data-time="07:00">07:00</td>
</tr>
<tr>
<td data-day="0" data-time="08:00" data-selected="true">08:00</td>
<td data-day="1" data-time="08:00">08:00</td>
</tr>
<tr>
<td data-day="0" data-time="09:00" data-selected="true">09:00</td>
<td data-day="1" data-time="09:00" data-selected="true">09:00</td>
</tr>
<tr>
<td data-day="0" data-time="10:00" data-selected="true">10:00</td>
<td data-day="1" data-time="10:00" data-selected="true">10:00</td>
</tr>
<tr>
<td data-day="0" data-time="11:00" data-selected="true">11:00</td>
<td data-day="1" data-time="11:00" data-selected="true">11:00</td>
</tr>
<tr>
<td data-day="0" data-time="12:00">12:00</td>
<td data-day="1" data-time="12:00" data-selected="true">12:00</td>
</tr>
<tr>
<td data-day="0" data-time="13:00">13:00</td>
<td data-day="1" data-time="13:00">13:00</td>
</tr>
<tr>
<td data-day="0" data-time="14:00">14:00</td>
<td data-day="1" data-time="14:00">14:00</td>
</tr>
<tr>
<td data-day="0" data-time="15:00">15:00</td>
<td data-day="1" data-time="15:00">15:00</td>
</tr>
<tr>
<td data-day="0" data-time="16:00">16:00</td>
<td data-day="1" data-time="16:00">16:00</td>
</tr>
<tr>
<td data-day="0" data-time="17:00">17:00</td>
<td data-day="1" data-time="17:00">17:00</td>
</tr>
<tr>
<td data-day="0" data-time="18:00">18:00</td>
<td data-day="1" data-time="18:00">18:00</td>
</tr>
<tr>
<td data-day="0" data-time="19:00">19:00</td>
<td data-day="1" data-time="19:00">19:00</td>
</tr>
<tr>
<td data-day="0" data-time="20:00">20:00</td>
<td data-day="1" data-time="20:00" data-selected="true">20:00</td>
</tr>
<tr>
<td data-day="0" data-time="21:00">21:00</td>
<td data-day="1" data-time="21:00" data-selected="true">21:00</td>
</tr>
<tr>
<td data-day="0" data-time="22:00">22:00</td>
<td data-day="1" data-time="22:00" data-selected="true">22:00</td>
</tr>
<tr>
<td data-day="0" data-time="23:00">23:00</td>
<td data-day="1" data-time="23:00" data-selected="true">23:00</td>
</tr>
</tbody>
</table>

Sum table values based on grouping

I have the following table:
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
I need a way to add/sum all values grouped by category, ie: add/sum all values in cat1, then add/sum all values in cat2. For each group I will do something with the total.
So I was hoping for something like:
for each unique category:
sum values in category
do something with this category total
For cat1 the total would be 123 + 486. Cat2 would just be 356. And so on if there were more categories.
I would prefer a purely javascript solution, but JQuery will do if that's not possible.
If I understand you correctly, you do a repeat of each td:first-child (The category cell).
Create a total object. You can check if the category is exist in it for each cell. If so, add current value to the stored value. If not, insert new property to it.
Like this:
var total = {};
[].forEach.call(document.querySelectorAll('td:first-child'), function(td) {
var cat = td.getAttribute('class'),
val = parseInt(td.nextElementSibling.innerHTML);
if (total[cat]) {
total[cat] += val;
}
else {
total[cat] = val;
}
});
console.log(total);
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
Here's a simple approach using only javascript
//grab data
var allTR = document.getElementsByTagName('TR');
var result = {};
//cycle table rows
for(var i=0;i<allTR.length;i+2){
//read class and value object data
var class = allTR[i].getAttribute('class');
var value = allTR[i+1].innerText;
//check if exists and add, or just add
if(result[class])
result[class] += parseInt(value);
else
result[class] = parseInt(value);
}
You have to use getElementsByTagName("td"); to get all the <td> collection and then you need to loop through them to fetch their innerText property which later can be summed up to get the summation.
Here is the working Fiddle : https://jsfiddle.net/ftordw4L/1/
HTML
<table id="tbl1">
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
<tr>
<td class="total"><b>Total</b></td>
<td class="totalValue"></td>
</tr>
</table>
Javascript
var tds=document.getElementsByTagName("td");
var total=0;
for (var i = 0; i<tds.length; i++) {
if (tds[i].className == "value") {
if(total==0) {
total = parseInt(tds[i].innerText);
} else {
total = total + parseInt(tds[i].innerText);
}
}
}
document.getElementsByClassName('totalValue')[0].innerHTML = total;
Hope this helps!.
here is a solution with jQuery :) if you are interested. it's pretty straightforward
var sumCat1 = 0;
var sumCat2 = 0;
$(".cat1 + .value").each(function(){
sumCat1 += parseInt($(this).text());
})
$(".cat2 + .value").each(function(){
sumCat2 += parseInt($(this).text());
})
console.log(sumCat1)
console.log(sumCat2)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
A simple approach in JQuery...
var obj = {};
$('tr').each(function() {
$this = $(this)
if ($this.length) {
var cat = $(this).find("td").first().html();
var val = $(this).find("td").last().html();
if (cat) {
if (!obj[cat]) {
obj[cat] = parseInt(val);
} else {
obj[cat] += parseInt(val);
}
}
}
})
console.log(obj)

How To Sum All Table Rows td (TotalPrice) using td id Jquery

I am adding values to table like:
Item,Quantity,Price,TotalPrice
Now there are multiple rows: How can i sum TotalPrice of all to get GrandTotal using Jquery.
Code:
$("#Product").append(" <tr><td id='clientname'>" +ClientName+ "</td> <td id='item'>"+ItemName+"</td> <td id='quantity'>"+Quantity+"</td> <td id='price'>"+Price+"</td> <td id='totalprice'>"+TotalPrice+"</td> <td> <a onClick='deleteRow(this);'>Delete</a> </td> </tr>");
Its possible when i insert new row data its show grand total in textbox/label,Like:
function TotalPriceCalc()
{
var lblTotalPrice = document.getElementById('lblTotalPrice');
lblTotalPrice.value = sum;
}
Here's an example that will sum whatever column index you provide.
$(function() {
$("#subtotal").html(sumColumn(4));
$("#total").html(sumColumn(5));
});
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="border-spacing: 10px;">
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>12</td>
<td>34</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>56</td>
<td>78</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>90</td>
<td>12</td>
</tr>
<tr>
<td colspan="3">Totals</td>
<td id="subtotal"></td>
<td id="total"></td>
</tr>
</table>
After you use class= instead of id= .Cause ID MUST be unique. you need to loop through each row and find totalPrice
$(document).ready(function(){
var TotalValue = 0;
$("#Product tr").each(function(){
TotalValue += parseFloat($(this).find('.totalprice').text());
});
alert(TotalValue);
});
While you tagged Jquery .. This is a Jquery solution so please be sure to include Jquery
You should use classes, not IDs, to name repeated elements. So it should be:
...<td class="totalprice">'+TotalPrice+'</td>...
Then you can do
function TotalPriceCalc() {
var total = 0;
$(".totalprice").each(function() {
total += parseFloat($(this).text());
});
$("#lblTotalPrice").val(total);
}
Have look, this is our table
<table class="table table-bordered">
<thead>
<tr>
<th>1</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="loop">50</td>
</tr>
<tr>
<td>1</td>
<td id="loop">60</td>
</tr>
<tr>
<td>1</td>
<td id="loop">70</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="text-right">Total</td>
<td></td>
</tr>
</tbody>
And this is loop to have sum of price
$(function() {
var TotalValue = 0;
$("tr #loop").each(function(index,value){
currentRow = parseFloat($(this).text());
TotalValue += currentRow
});
console.log(TotalValue);
});

Lots of NaN and incorrect values in a block of jQuery?

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.

Categories