i need to calculate grand total from sub total, - javascript

I'm using table for invoice, dynamically adding new row and deleting row option, my code work well for calculation of "quantity * productprice =tcost" each row, but I need to calculate grand total from subtotal, can anyone suggest me how to write code.
This is my script:
<script>
(function() {
"use strict";
$("table").on("change", "input", function() {
var row = $(this).closest("tr");
var qty = parseFloat(row.find(".quantity").val());
var price = parseFloat(row.find(".productprice").val());
var tcost = qty * price;
row.find(".tcost").val(isNaN(tcost) ? "" : tcost);
});
})();
</script>
my table:
<table class="table table-bordered inventory" style="width:95%;float:right;">
<thead>
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
<th>S. No</th>
<th>Product Name</th>
<th>Item Code</th>
<th>Quantity</th>
<th>Price per Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr for="input01">
<td><input type='checkbox' class='case'/></td>
<td><span id='snum'>1.</span></td>
<td><input type='text' id='productname_1' name='productname[]' required/></td>
<td><input type='text' id='itemcode_1' name='itemcode[]' required/></td>
<td><input type='text' class="quantity" id='quantity_1' name='quantity[]' style="width:165px;"required/></td>
<td><input type='text' class="productprice" id='productprice_1' name='productprice[]'style="width:165px;" required/></td>
<td><input type='text' class="tcost" id='tcost_1' name='tcost[]'style="width:165px;" /> </td>
</tr>
</tbody>
</table>
<input type='text' id='total' name='total' placeholder="Total amount" class="total" id="total"style="margin-left: 51px;"/>

I made this JSFIDDLE for you. Is that what you are asking for?
var totalValue = 0;
$(document).find(".tcost").each(function(){
totalValue += parseFloat($(this).val());
});
$("#total").val(totalValue);
JSFIDDLE

<script>
(function() {
function summarize() {
var total = 0;
$(".tcost").each(function() {
total += parseFloat($(this).val());
});
$("#total").val(total);
}
"use strict";
$("table").on("change", "input", function() {
var row = $(this).closest("tr");
var qty = parseFloat(row.find(".quantity").val());
var price = parseFloat(row.find(".productprice").val());
var tcost = qty * price;
row.find(".tcost").val(isNaN(tcost) ? "" : tcost);
summarize();
});
})();
</script>

Related

How to adjust this number input field's format to either USD (period as separator) or COP (comma as separator) dynamically in JS?

The table has an input field, which, depending on the currency passed, it's supposed to have either a comma or a period as decimal separator.
I have tried setting it initally to either lang="es" or lang="en", but it doesn't change.
I'd appreciate a little help!
function add_to_total(el, currency) {
currency = 'es'
let rowTotal = 0;
let currencyFormat = currency == 'en' ? Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}) : Intl.NumberFormat("es-CO", {
style: "currency",
currency: "COP",
})
if (el) {
let parent = $(el).closest('tr'),
price = parent.find('.price').val(),
qty = parent.find('.qty').val();
if (price == '' || qty == '') {
alert('Please make sure that the price and metros are informed correctly.');
return;
}
rowTotal = (qty * price).toFixed(2);
parent.find('.total_price').html(currencyFormat.format(rowTotal));
} else {
$("#tableRows tr").each(function() {
price = parseFloat($(this).find('.qty').val());
qty = parseFloat($(this).find('.price').val());
if (price && qty) {
rowTotal = (price * qty).toFixed(2);
$(this).find('.total_price').text(currencyFormat.format(rowTotal));
}
});
}
var gridTotal = 0;
$(".total_price").each(function(index, item) {
var val = parseFloat($(this).html().replace(/[$,]/g, ''));
if (isNaN(val)) val = 0;
gridTotal += val;
});
$('.total').html(currencyFormat.format(gridTotal.toFixed(2)));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover table-vcenter" id="dtable">
<thead>
<tr>
<th style="width:7%">Precio/m (USD)</th>
<th style="width:8%">Metros (m)</th>
<th style="width:10%">Precio Total sin IVA (COP)</th>
</tr>
</thead>
<tbody id="tableRows">
<tr>
<td><input type="number" step="0.01" min="0" class="price" name="numberInputs" value="" onchange="add_to_total(this);"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="0" onchange="add_to_total(this);'=""></td>
<td class=" total_price"><strong>0.00</strong></td>
</tr>
<tr>
<td><input type="number" step="0.01" min="0" class="price" name="numberInputs" value="" onchange="add_to_total(this);"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="0" onchange="add_to_total(this)"></td>
<td class="total_price"><strong>0.00</strong></td>
</tr>
</tbody>
<tbody>
<tr>
<td id="totalTitle" colspan="8" align="right"><strong>Total:</strong></td>
<td id="totalValue" class="total">0.00</td>
</tr>
</tbody>
</table>

How I can get the one table value row by row and then show these values in another table using jquery

i am trying this code to fetch row by row value and perform calculation on those value but we get the result in last row that and show last row result in every row of table 2.
$(document).ready(function() {
$("#tbUser").on('click', '.btnDelete', function() {
var idx = $(this).closest('tr').index();
$("#tbUser").find("tr").eq(idx).remove();
$("#tbUsers").find("tr").eq(idx - 1).remove();
});
$("#tbUser").on('click', '.btnAdd', function() {
$("#tbUser").append("<tr class='item'><td>Pad</td><td id='selection'>0.000307</td><td><input type='text' name='BottomHoleRate' id='BottomHoleRate'></td><td><input type='text' name='CleanVolume' id='CleanVolume'></td><td><input type='text' name='BottomHoleConcentration' id='BottomHoleConcentration'></td><td>v 2.2</td><td><input type='text' name='Chemvol' id='Chemvol'></td><td><button class='btnAdd'>Add</button></td><td><button class='btnDelete'>Delete</button></td></tr>");
$("#tbUsers").append("<tr><td><input type='text' name='StageTime' id='StageTime' value=''></td><td><input type='text' name='SlurryRate' id='SlurryRate'></td><td><input type='text' name='CleanRate' id='CleanRate'></td><td><input type='text' name='BlenderConcentration' id='BlenderConcentration'></td><td><input type='text' name='ProppantVolumeRate' id='ProppantVolumeRate'></td><td><input type='text' name='ProppantMassRate' id='ProppantMassRate'></td><td><input type='text' name='ProppantAVG' id='ProppantAVG'></td><td><input type='text' name='ProppantStageMass' id='ProppantStageMass'></td><td><input type='text' name='ProppantCumulativeMass' id='ProppantCumulativeMass'></td><td><input type='text' name='ProppantVolume' id='ProppantVolume'></td><td><input type='text' name='ProppantCumulativeVolume' id='ProppantCumulativeVolume'></td><td><input type='text' name='SlurryStageVolume' id='SlurryStageVolume'></td><td><input type='text' name='SlurryCumulativeVolume' id='SlurryCumulativeVolume'></td></tr>");
$("#tbUsers2").append("<tr><td>Pad</td></tr>");
$("#tbUsers3").append("<tr><td>Pad</td></tr>");
});
});
$('button').on('click', function() {
$("#tbUser tr.item").each(function() {
var BottomHoleRate = $(this).find("input[name='BottomHoleRate']").val(),
CleanVolume = $(this).find("input[name = 'CleanVolume']").val();
bhc = $(this).find("input[name = 'BottomHoleConcentration']").val();
Chemvol = $(this).find("input[name = 'Chemvol']").val();
// SlurryStageVolume=document.getElementById('SlurryStageVolume').value;
SlurryRate = BottomHoleRate;
blenderconcentration = bhc;
ProppantAVG = document.getElementById('selection').innerText;
proppant_stage_mass = CleanVolume * bhc;
pro_cum_mass = proppant_stage_mass;
proppant_vol = proppant_stage_mass * ProppantAVG;
pro_cum_vol = proppant_vol;
slurry_stage_vol = CleanVolume * (1 + ProppantAVG * bhc);
slurry_cum_vol = slurry_stage_vol;
cleanrate = SlurryRate / (1 + ProppantAVG + bhc);
stage = slurry_stage_vol / SlurryRate;
proppant_vol_rate = cleanrate * bhc * ProppantAVG;
proppant_mass_rate = cleanrate * bhc;
chem_rate1 = Chemvol * cleanrate;
chem_vol = Chemvol * CleanVolume;
$('input[name="StageTime"]').val(stage);
$('input[name="SlurryRate"]').val(SlurryRate);
$('input[name="CleanRate"]').val(cleanrate);
$('input[name="BlenderConcentration"]').val(blenderconcentration);
$('input[name="ProppantVolumeRate"]').val(proppant_vol_rate);
$('input[name="ProppantMassRate"]').val(proppant_mass_rate);
$('input[name="ProppantAVG"]').val(ProppantAVG);
$('input[name="ProppantStageMass"]').val(proppant_stage_mass);
$('input[name="ProppantCumulativeMass"]').val(pro_cum_vol);
$('input[name="ProppantVolume"]').val(proppant_vol);
$('input[name="ProppantCumulativeVolume"]').val(pro_cum_vol);
$('input[name="SlurryStageVolume"]').val(slurry_stage_vol);
$('input[name="SlurryCumulativeVolume"]').last().val(slurry_cum_vol);
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<table id="tbUser" class="tblUser" name="tblUser">
<tr>
<td><button class="btnDelete">Delete</button></td>
<td><button class="btnAdd">Add</button></td>
</tr>
<tr>
<th>Stage Name</th>
<th>Proppant Selection</th>
<th>Bottom Hole Rate</th>
<th>Clean Volume</th>
<th>Bottom Hole Concentration</th>
<th>Quality</th>
<th>Chem 1 Vol/Vol</th>
</tr>
</table>
<h2>table 2</h2>
<table id="tbUsers">
<tr>
<th>Stage Time (min)</th>
<th>Slurry Rate</th>
<th>Clean Rate</th>
<th>Blender Concentration</th>
<th>Proppant Volume Rate</th>
<th>Proppant Mass Rate</th>
<th>Proppant AVG</th>
<th>Proppant Stage Mass</th>
<th>Proppant Cumulative Mass</th>
<th>Proppant Volume</th>
<th>Proppant Cumulative Volume</th>
<th>Slurry Stage Volume</th>
<th>Slurry Cumulative Volume</th>
</tr>
</table>
<h2>table 3</h2>
<table id="tbUsers2">
<tr>
<th>Chem rate 1</th>
</tr>
</table>
<h2>table 4</h2>
<table id="tbUsers3">
<tr>
<th>Chem Volume 1</th>
</tr>
</table>
<input type="button" name="submit" value="submit" />
<button>submit</button>
I want to show these value in another table row by row, means the first-row value show in the first row of another table and 2nd-row value show in the 2nd row of another table and so on.

How to get value of checkbox in table?

How can I get value of checkbox in table? I want use it for in this case in order get parameter. Now, please see html table:
<table id="div_func" class="table table-bordered" style="width: 100%">
<thead>
<tr>
<th>
<input type="checkbox" id="chk_all" /></th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="D01" /></td>
<td>Banana </td>
</tr>
<tr>
<td> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="D02" /></td>
<td>Orange </td>
</tr>
<tr>
<td> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="D03" /></td>
<td>Apple </td>
</tr>
</tbody>
</table>
And this is my script , I use for get value in checkbox , then put parameter
function add_funcgroup() {
var func_group = [];
var chk_allow = "";
var table = document.getElementById("div_func");
for (var i = 0; i < table.rows.length; i++) {
if ($('#chk')[i].is(':checked')) {
chk_allow = "True";
}
else {
chk_allow = "False";
}
var group_func = {
GROUP_MOD_ID: id_temp,
FUNCTION_MOD_ID: $('#chk')[i].val(),
ALLOW: chk_allow
};
func_group[i] = group_func;
}
var func_group_temp = {
FUNC_MOD: func_group
};
var DTO = {
'func_group_temp': func_group_temp
};
$.ajax(
{
And it's not working.
What you have done is right, but you are not outputting it to the table!
var table = $("#div_func");
var value_check = "";
for (var i = 1; i < table.rows.length; i++) {
if ($('#chk')[i].is(':checked')) {
value_check += i + ": " + $('#chk')[i].val();
}
}
alert(value_check);
And you aren't appending it, instead saving!
Try to this
$('#div_func tbody tr input:checkbox').each(function() {
if (this.checked) {
//Do something
}
});.

Clone a row in an HTML table and call JavaScript function with the new row

I have a table which has one row in which I multiply two fields, namely quantity and rate/quantity, to get the product total. I have provided a button to add a new row which basically clones the 1st row. Now I want the cloned row to also have the same product as the 1st row. I have tried the following code:
<!DOCTYPE html>
<html>
<h3 align="center">K J Somaiya College Of Engineering, Vidyavihar, Mumbai-400 077</h3>
<h3 align="center">Department Of Information Technology</h3>
<body>
<script>
function WO1() {
var qty = document.getElementById('qty').value;
var price = document.getElementById('price').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice').value = answer;
}
function WO2() {
var qty = document.getElementById('qty1').value;
var price = document.getElementById('price1').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice1').value = answer;
}
function WO3() {
var qty = document.getElementById('qty2').value;
var price = document.getElementById('price2').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice2').value = answer;
}
</script>
<script>
function validateNumbe()
{
var x=document.getElementById("floor").value;
if (x==null || x=="")
{
alert("Floor must be entered");
return false;
}
}
function validateN()
{
var x=document.getElementById("lab").value;
if (x==null || x=="")
{
alert("Laboratory Name must be entered");
return false;
}
}
function validateNumb()
{
var x=document.getElementById("room").value;
if (x==null || x=="")
{
alert("Room No must be entered");
return false;
}
}
function validateNum()
{
var x=document.getElementById("labi").value;
if (x==null || x=="")
{
alert("Name of Laboratory Incharge must be entered");
return false;
}
}
function validateNu()
{
var x=document.getElementById("year").value;
if (x==null || x=="")
{
alert("Budget for the year must be entered");
return false;
}
}
</script>
<table width="100%" cellspacing="10">
<tr>
<td align="left">Date:<input type="date" name="date"/></td>
<td align="right">Floor: <input type="text" id="floor" onchange="validateNumbe()"
onblur="validateNumbe()"/> </td>
</tr>
<tr>
<td align="left">Laboratory Name: <input type="text" id="lab" onchange="validateN()"
onblur="validateN()"/></td>
<td align="right">Room no: <input type="text" id="room" onchange="validateNumb()"
onblur="validateNumb()"/></td>
</tr>
<tr>
<td align="left">Name of Laboratory Incharge: <input type="text" id="labi"
onchange="validateNum()" onblur="validateNum()"/></td>
<td align="right">Budget for the year: <input type="text" id="year" onchange="validateNu()"
onblur="validateNu()"/></td>
</tr>
</table>
<h3 align="left"><b>Computer</b><h3>
<table id="POITable" border="1" width="100%">
<tr>
<td style="width:10%">Sr No.</td>
<td>Item Description</td>
<td>Quantity</td>
<td>Rate(Inclusive of Taxes)</td>
<td>Total Cost</td>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price' class="price" placeholder='Price (£)'
onChange="WO1()" /></td>
<td><input type='text' name='Total' id='totalprice' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton" value="Add New Row"/>
<h3 align="left"><b>Equipment</b><h3>
<table id="POITable1" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty1' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price1' class="price" placeholder='Price (£)'
onChange="WO2()" /></td>
<td><input type='text' name='Total' id='totalprice1' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton1" value="Add New Row"/>
<h3 align="left"><b>Furniture</b><h3>
<table id="POITable2" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty2' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price2' class="price" placeholder='Price (£)'
onChange="WO3()" /></td>
<td><input type='text' name='Total' id='totalprice2' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton2" value="Add New Row"/>
<script>
( function() { // Prevent vars from leaking to the global scope
var formTable = document.getElementById('POITable');
var newRowBtn = document.getElementById('addmorePOIbutton');
newRowBtn.addEventListener('click', insRow, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow() {
var new_row = formTable.rows[1].cloneNode(true),
numTableRows = formTable.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable.appendChild( new_row );
}
var formTable1 = document.getElementById('POITable1');
var newRowBtn1 = document.getElementById('addmorePOIbutton1');
newRowBtn1.addEventListener('click', insRow1, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow1() {
var new_row = formTable1.rows[1].cloneNode(true),
numTableRows = formTable1.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable1.appendChild( new_row );
}
var formTable2 = document.getElementById('POITable2');
var newRowBtn2 = document.getElementById('addmorePOIbutton2');
newRowBtn2.addEventListener('click', insRow2, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow2() {
var new_row = formTable2.rows[1].cloneNode(true),
numTableRows = formTable2.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable2.appendChild( new_row );
}
})();
function myfun()
{
var lun= document.getElementById('POITable').rows.length;
document.getElementsByName("len")[0].value = lun-1;
var lun1= document.getElementById('POITable1').rows.length;
document.getElementsByName("len1")[0].value = lun1-1;
var lun2= document.getElementById('POITable2').rows.length;
document.getElementsByName("len2")[0].value = lun2-1;
}
function myFunction()
{
window.print();
}
</script>
<input type="hidden" name="len" value="1">
<input type="hidden" name="len1" value="1">
<input type="hidden" name="len2" value="1">
<table width="100%">
<tr>
<td><br><br><br></td>
<td><br><br><br></td>
<td><br><br><br></td>
</tr>
<tr>
<td align="left">Signature <br>Lab-In-Charge</td>
<td align="center">Signature<br>Lab Assistant</td>
<td align="right">Signature <br>Head of Department</td>
</tr>
</table>
<br><br><br>
<input type="submit" value="SUBMIT" onclick='this.form.action="archive.php";myfun();'>
<input type="submit" value="SAVE AND CONTINUE LATER"
onclick='this.form.action="myphpformhandler.php";myfun();'>
</form>
<h3 align="center"><button onclick="myFunction()"><h3>Print this page</h3></button></h3>
</body>
</html>
i have created the JSFiddle but the multiplication is not working in it.
http://jsfiddle.net/xkY4Z/2/
Not a perfect solution to your problem but a bit closer Working Fiddle
Done using jQuery
$(document).on('change','input', function () {
var id = $(this).attr('id').split("-");
var answer = (Number($('#qty-' + id[1]).val()) * Number($('#price-' + id[1]).val())).toFixed(2);
$('#totalprice-' + id[1]).val(answer);
});
Update
Working Fiddle with name
Latest
Fiddle with Grand total

Calculate table rows and populate the grand total field

I have table like below :
<table>
<thead>
<th>Product Type</th>
<th>Quantity</th>
<th>Unit</th>
<th>Total</th>
</thead>
<tr>
<td>Gas</td>
<td><input type="text" name="qty" /></td>
<td>
<select id="unit" name="unit">
<option value="30.42">Liter</option>
<option value="25.30">Ton</option>
<option value="45.10">Kg</option>
</td>
<td><input type="text" readonly="readonly" name="total" /></td>
</tr>
<tr>
<td>Diesel</td>
<td><input type="text" name="qty" /></td>
<td>
<select id="unit" name="unit">
<option value="20.42">Liter</option>
<option value="18.30">Ton</option>
<option value="25.10">Kg</option>
</td>
<td><input type="text" readonly="readonly" name="total" /></td>
</tr>
<tr>
<td>Fuel</td>
<td><input type="text" name="qty" /></td>
<td>
<select id="unit" name="unit">
<option value="30.42">Liter</option>
<option value="25.30">Ton</option>
<option value="45.10">Kg</option>
</td>
<td><input type="text" readonly="readonly" name="total" /></td>
</tr>
I would like to calculate ( qty * unit ) each row based qty and unit and put the result total column.
At the end of the calculation, I want to sum whole total fields and put the Grand Total field.
I tried like below which is always returning NaN but when I checked the value by typeof returning number!!! :
$(document).ready(function() {
$('input[name^=qty], select[name^=unit]').change(function(){
var total = 0;
var $row = $(this).parent();
var qty = parseFloat($row.find('input[name=qty]').val());
var price = parseFloat($row.find("select[name='unit'] option:selected").val());
total = parseFloat(qty * price);
$row.find('.amount').text(parseFloat(qty * price));
})
});
There are several errors here, including using text() on an input field, and using parent() instead of closest("tr").
I've also added classes to your elements to make the selectors easier. Try this:
$('.qty, .unit').change(function(){
var total = 0;
var $row = $(this).closest("tr");
var qty = parseFloat($row.find('.qty').val());
var price = parseFloat($row.find(".unit").val());
total = parseFloat(qty * price);
$row.find('.total').val(parseFloat(qty * price));
})
Example fiddle
UPDATE
Added blank default to selects:
$('.qty, .unit').change(function(){
var total = 0;
var $row = $(this).closest("tr");
var qty = parseFloat($row.find('.qty').val());
var price = parseFloat($row.find(".unit").val());
total = qty * price;
if (isNaN(total)) {
$row.find('.total').val("");
}
else {
$row.find('.total').val(total);
}
})
Fiddle
Instead of var $row = $(this).parent(); try
var $row = $(this).closest("tr");
The code you have is looking at the td and you need to find the tr. Closest looks for the closest match up the DOM tree.
Try this,not tested
$(document).ready(function() {
$('input[name^=qty], select[name^=unit]').change(function(){
var total = 0;
var $row = $(this).parent().prev(); //changed here
var qty = parseFloat($row.find('input[name=qty]').val());
var price = parseFloat($row.find("select[name='unit'] option:selected").val());
total = parseFloat(qty * price);
$row.find('.amount').text(parseFloat(qty * price));
})
});

Categories