I have created a form to calculate the price times the quantity of a item. It had more choices but I narrowed it down to one choice. But now I can't figure out how give price breaks for more quantity. Basically there are price breaks as follows:
Item A is 4.60 for 1+ item. For 10+ items 3.40, 25+ 2.68 and so on until it hits 5000+ items. This is the same for items, B and C except they are priced different.
How can I calculate this using the method below:
Html Form:
<form action="#" id="price-quote" onsubmit="return false">
<table width="501" border="0" cellpadding="10" cellspacing="20" style="padding- top:30px;">
<tr>
<th width="67" scope="row">Size:</th>
<td width="273" class="select-box"> <select id="size" name="size">
<option value="None">Select Size</option>
<option value="2.5 inches">2.5 inches</option>
<option value="3 inches">3 inches</option>
<option value="Oval">Oval</option>
</select>
</td>
</tr>
<tr>
<th scope="row">Quanitity:</th>
<td><input type="text" name="quantity" id="quantity" /></td>
</tr>
<tr>
<th scope="row"> </th>
<td><input class="button" type="button" value="Update" onmousedown="getTotal()"/></td>
</tr>
<tr>
<th> Price:</th>
<td><div id="totalPrice" style="float:right;"></div></td>
</tr>
</table>
</form>
Javascript:
var size_prices= new Array();
size_prices["None"]=0;
size_prices["2.5 inches"]=4.60;
size_prices["3 inches"]=4.90;
size_prices["Oval"]=5.10;
function getSizePrice()
{
var sizePrice;
var theForm = document.forms["price-quote"];
var selectedSize = theForm.elements["size"];
sizePrice = size_prices[selectedSize.value];
return sizePrice;
}
function getQuantity()
{
var theForm = document.forms["price-quote"];
//Get a reference to the TextBox
var quantity = theForm.elements["quantity"];
var howmany =0;
//If the textbox is not blank
if(quantity.value!="")
{
howmany = parseInt(quantity.value);
}
return howmany;
}
function getTotal()
{
var instantPrice = getSizePrice() * getQuantity();
document.getElementById('totalPrice').innerHTML =
"$"+instantPrice.toFixed(2);
}
Could someone please point me in the right direction. Thank you
function getTotal()
{
var q = getQuantity();
var unitPrice = 4.60;
if(q >= 10){
unitPrice = 3.40;
} else if (q >= 25){
unitPrice = 2.68;
}
var instantPrice = unitPrice * q;
document.getElementById('totalPrice').innerHTML =
"$"+instantPrice.toFixed(2);
}
Related
I have created a very simple table in HTML. The column "Sector" has 4 possible selections in a drop down list. I type manually the amount of money in the second column. What I want to do is to display Total Money in the third column, which should be:
Total money = (Amount of money) * 1, in case that Sector = Footbal (and therefore value "s1")
Total money = (Amount of money) * 9, in any other case
For some reason it multiplies always by 9. How can I make this work?
function getValue() {
var selectedValue1 = document.querySelectorAll(".sector");
if (selectedValue1 == 's1') {
CONSTANT = 1;
} else {
CONSTANT = 9;
}
}
var Initial = document.querySelectorAll('.number1');
var Double = document.querySelectorAll('.number2');
Initial.forEach(myFunction);
function myFunction(item, index) {
getValue()
item.addEventListener('change', (event) => {
var initialValue = event.target.value;
Double[index].value = initialValue * CONSTANT;
});
}
<! --COMIENZO TABLA -->
<table class="egt">
<! --SEGUNDA LINEA -->
<tr>
<th>Sector</th>
<th>Amount of money</th>
<th>Total money</th>
</tr>
<! --TERCERA LINEA -->
<tr>
<td>
<select class="sector">
<option value="s1">Football</option>
<option value="s2">Basketball</option>
<option value="s3">Volleyball</option>
<option value="s4">Rugby</option>
</select>
</td>
<td>
<input type="number" class="number1">
</td>
<td>
<input type="number" class="number2">
</td>
</tr>
<! --CUARTA LINEA -->
<tr>
<td>
<select class="sector">
<option value="s1">Football</option>
<option value="s2">Basketball</option>
<option value="s3">Volleyball</option>
<option value="s4">Rugby</option>
</select>
</td>
<td>
<input type="number" class="number1">
</td>
<td>
<input type="number" class="number2">
</td>
</tr>
</table>
<! --FINAL TABLA -->
You should delegate and get the value from the select on change
I added thead and tbody
const table = document.querySelector(".egt");
table.addEventListener("input", function(e) { // when ANYTHING changes
[...table.querySelectorAll("tbody tr")].forEach(row => { // loop over all rows
const sectorValue = row.querySelector(".sector").value == 's1' ? 1 : 9; // from this row
const num1 = row.querySelector(".number1").value;
row.querySelector(".number2").value = num1 * sectorValue;
});
})
<! --COMIENZO TABLA -->
<table class="egt">
<thead>
<! --SEGUNDA LINEA -->
<tr>
<th>Sector</th>
<th>Amount of money</th>
<th>Total money</th>
</tr>
</thead>
<! --TERCERA LINEA -->
<tbody>
<tr>
<td>
<select class="sector">
<option value="s1">Football</option>
<option value="s2">Basketball</option>
<option value="s3">Volleyball</option>
<option value="s4">Rugby</option>
</select>
</td>
<td>
<input type="number" class="number1">
</td>
<td>
<input type="number" class="number2">
</td>
</tr>
<! --CUARTA LINEA -->
<tr>
<td>
<select class="sector">
<option value="s1">Football</option>
<option value="s2">Basketball</option>
<option value="s3">Volleyball</option>
<option value="s4">Rugby</option>
</select>
</td>
<td>
<input type="number" class="number1">
</td>
<td>
<input type="number" class="number2">
</td>
</tr>
</tbody>
</table>
<! --FINAL TABLA -->
NOTE: I use the spread operator [...collection] to convert an HTML Collection into an array - it is to handle older EDGE browsers which do not have native forEach on a collection. You can do table.querySelectorAll("tbody tr").forEach() if you do not care to support older Edge
Your cade has some fundamental problems (f.e. since selectedValue1 is a Node list, it can't be equal to "s1"), but also your approach is incorrect.
I don't see any reason to create loop here, but if need it:
Loop through each row, and then get the value of selection as well as number, and calculate the output and set it. This is easier and the correct way.
First, Give your table thead and tbody tags to create a wrapper around data.
let CONSTANT = 1;
let rows = document.querySelectorAll("tbody tr");
[...rows].forEach(row => {
let selection = row.querySelector(".sector").value;
CONSTANT = selection === "s1" ? 1 : 9;
let number = row.querySelector(".number1").value;
row.querySelector(".number2").value = CONSTANT * number;
})
But this is also not the best way. Instead of looping, just add event listeners and call a function to calculate.
let rows = document.querySelectorAll("tbody tr");
[...rows].forEach(row => {
row.querySelector(".number1").addEventListener("input", () => {
calculate(row)
})
row.querySelector(".sector").addEventListener("change", () => {
calculate(row)
});
})
function calculate(row) {
let constant = row.querySelector(".sector").value === "s1" ? 1 : 9;
let num1 = row.querySelector(".number1").value;
row.querySelector(".number2").value = constant * num1;
}
How to count 1 option selected in dropdown from different rows and display count in textbox?
I would like to count total value casualties of different rows and display count of total value casualties in textbox id injury.
Codes for dropdownlist && textbox && add row:
<select name="type" id="dd">
<option>Select a Type</option>
<option value="casualties">Casualties</option>
<option value="notcasualties">Not Casualties</option>
</select>
</select>
<label>Casualties:</label><input type="text" id="injury">
<btn><input type="button" value="addrow" onclick="addrow('dataTable2')" /></btn>
This codes are only able to display count = 1 in textbox id injury for the first row but not the added rows. I would like to total up count of value casualties after different rows are added. Could anyone help me.
$('#dd').change(function(){
var count = $('#dd option:selected').length;
$('.injury').val(count);
});
Thanks in advance!
Add onchange="select($(this).val())" in select tag and following function in script
function select(value){
if(value==="casualties"){
$("#injury").val(parseInt($("#injury").val())+1);
}
else{
$("#injury").val(parseInt($("#injury").val())-1);
if($("#injury").val()<0)
$("#injury").val("0");
}
}
and remove
$('#dd').change(function(){
var count = $('#dd option:selected').length;
$('.injury').val(count);
});
I made some changes that full fill your purpose
<html>
<head><title>table example</title></head>
<body>
<table id="dataTable2">
<tr>
<th></th>
<TH>Admin No/Staff ID:</TH>
<TH>Name:</TH>
<TH>Contact No:</TH>
<TH>Types of People Involved:</TH>
</TR>
<tr>
<td><input type="checkbox" name="checkbox[]"></td>
<TD><input type="text" name="id[]" id="id" /></TD>
<TD><input type="text" name="names[]" id="names"></TD>
<TD><input type="text" name="contacts[]" id="contacts" /> </TD>
<TD>
<select name="type" id="dd" class="selectpicker" data-style="select-with-transition" title="News Type" data-size="7" onchange="show()">
<option value="">Select a Type</option>
<option value="casualties" class="casualties-element">Casualties</option>
<option value="ncasualties">Non-Casualties</option>
<option value="witness">Witness</option>
</select>
</TD>
</tr>
</table>
<p>
<INPUT type="button" value="Add Row" onclick="addRow()" />
</p>
<table id="dataTable1" style="cellpadding:20px;">
<tr>
<th></th>
<TH>Admin No/Staff ID:</TH>
<TH>Name:</TH>
<TH>Contact No:</TH>
<TH>Types of People Involved:</TH>
</tr>
</table>
<p>
<label>No. of Casualties:</label>
<input type="text" name="injury" id="injury" class="injury span2" onClick="show();">
</p>
<script>
var count = 0;
function addRow() {
alert("test");
var table1 = document.getElementById('dataTable1');
var table = document.getElementById('dataTable2');
var did = document.getElementById('id').value;
var dname = document.getElementById('names').value;
var dcontact = document.getElementById('contacts').value;
var dddl = document.getElementById('dd');
var ddlvalue = dddl.options[dddl.selectedIndex].value;
if (ddlvalue == 'casualties') { count++; }
document.getElementById('injury').value = count;
var rowCount = table.rows.length;
//var row = table.insertRow(rowCount);
var row = table1.insertRow(1);
var colCount = table.rows[1].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
//newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (i) {
case 0:
newcell.innerHTML = did;
break;
case 1:
newcell.innerHTML = dname;
break;
case 2:
newcell.innerHTML = dcontact;
break;
case 3:
newcell.innerHTML = ddlvalue;
break;
}
}
}
</script>
</body>
</html>
I'm currently working on an invoice project.
So far I have a dynamic form where you can add and remove rows (see snippet below).
However I have a problem with my javascript, I was wondering if someone could help me out with it.
Basically, when you input the values into the form on the first row, it calculates it all perfectly. However, if you add a new row and try to fill it in with some data, the javascript doesn't seem to perform any calculation for that row. It only works for the first row and it's really frustrating me! I can't seem to figure out why.
Any help is much appreciated. The snippet of code is below and you can run it and add some data to some rows to see for yourself. I need any advice I can get on this.
Thanks in advance guys.
Snelly
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function calculate() {
var QTY = document.getElementById("Qty").value;
var LINEPRICENET = document.getElementById("LinePriceNet").value;
var LINEPRICEDISCOUNT = document.getElementById("LinePriceDiscountInput").value;
var TAXRATE = document.getElementById("TaxRate").value;
// Lineprice with discount
LINEPRICEWITHDISCOUNT = (QTY*(LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
document.getElementById('LinePriceWithDiscount').value = LINEPRICEWITHDISCOUNT.toFixed(2);
//Line Price discount Amount
LINEPRICEDISCOUNTAMOUNT = (QTY*(LINEPRICENET) - (QTY*(LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT)))));
document.getElementById("LinePriceDiscountAmount").value = LINEPRICEDISCOUNTAMOUNT.toFixed(2);
//Tax calculation
TAXAMOUNT = (LINEPRICEWITHDISCOUNT * TAXRATE);
document.getElementById("TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LINEPRICEWITHDISCOUNT + TAXAMOUNT);
document.getElementById("GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
}
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form name="CalculationTesting" >
<p>
<input type="button" value="Add Item" onClick="addRow('dataTable')" />
<input type="button" value="Remove Selected Item" onClick="deleteRow('dataTable')" />
</p>
<thead>
<tr>
<th>Qty</th>
<th>Line Price Net</th>
<th>Line Price Discount%</th>
<th>Line Price Discount Amount</th>
<th>Line Price With Discount</th>
<th>VAT Rate Amount</th>
<th>VAT Amount</th>
<th>Line Price Gross-OUTPUT</th>
</tr>
</thead>
<table id="dataTable" border="1" width="600" height="50" cellpadding="10" cellspacing="3">
<tr>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</td>
<td>
<input type="number" name="Qty" id="Qty" onchange="calculate();"/>
</td>
<td>
<input type="number" name="LinePriceNet" id="LinePriceNet" onchange="calculate();"/>
</td>
<td>
<select type="number" name="LinePriceDiscount" id="LinePriceDiscountInput" onchange="calculate();"/>
<option value="0.00">None</option>
<option value="0.01">1%</option>
<option value="0.02">2%</option>
<option value="0.03">3%</option>
<option value="0.04">4%</option>
<option value="0.05">5%</option>
<option value="0.06">6%</option>
<option value="0.07">7%</option>
<option value="0.08">8%</option>
<option value="0.09">9%</option>
<option value="0.10">10%</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceDiscountAmount" id="LinePriceDiscountAmount">
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceWithDiscount" id="LinePriceWithDiscount">
</td>
<td>
<select type="number" name="TaxRate" id="TaxRate" onchange="calculate();"/>
<option value="0.00">Zero Rate</option>
<option value="0.20">Standard(20%)</option>
<option value="0.00">Exempt</option>
<option value="0.05">Reduced Rate</option>
<option value="0.00">Outside The Scope</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="TaxAmount" id="TaxAmount">
</td>
<td>
<input readonly="readonly" type="number" name="GrossOutput" id="GrossOutput">
</td>
</tr>
</table>
</form>
</body>
</html>
I was able to fix it using following code. There might be cleaner version possible.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function calculate(object) {
var QTY = object.parentNode.parentNode.querySelector('#Qty').value;
var LINEPRICENET = object.parentNode.parentNode.querySelector("#LinePriceNet").value;
var LINEPRICEDISCOUNT = object.parentNode.parentNode.querySelector("#LinePriceDiscountInput").value;
var TAXRATE = object.parentNode.parentNode.querySelector("#TaxRate").value;
// Lineprice with discount
LINEPRICEWITHDISCOUNT = (QTY*(LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
object.parentNode.parentNode.querySelector('#LinePriceWithDiscount').value = LINEPRICEWITHDISCOUNT.toFixed(2);
//Line Price discount Amount
LINEPRICEDISCOUNTAMOUNT = (QTY*(LINEPRICENET) - (QTY*(LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT)))));
object.parentNode.parentNode.querySelector("#LinePriceDiscountAmount").value = LINEPRICEDISCOUNTAMOUNT.toFixed(2);
//Tax calculation
TAXAMOUNT = (LINEPRICEWITHDISCOUNT * TAXRATE);
object.parentNode.parentNode.querySelector("#TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LINEPRICEWITHDISCOUNT + TAXAMOUNT);
object.parentNode.parentNode.querySelector("#GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
}
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form name="CalculationTesting" >
<p>
<input type="button" value="Add Item" onClick="addRow('dataTable')" />
<input type="button" value="Remove Selected Item" onClick="deleteRow('dataTable')" />
</p>
<thead>
<tr>
<th>Qty</th>
<th>Line Price Net</th>
<th>Line Price Discount%</th>
<th>Line Price Discount Amount</th>
<th>Line Price With Discount</th>
<th>VAT Rate Amount</th>
<th>VAT Amount</th>
<th>Line Price Gross-OUTPUT</th>
</tr>
</thead>
<table id="dataTable" border="1" width="600" height="50" cellpadding="10" cellspacing="3">
<tr>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</td>
<td>
<input type="number" name="Qty" id="Qty" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);"/>
</td>
<td>
<input type="number" name="LinePriceNet" id="LinePriceNet" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);"/>
</td>
<td>
<select type="number" name="LinePriceDiscount" id="LinePriceDiscountInput" onchange="calculate(this);"/>
<option value="0.00">None</option>
<option value="0.01">1%</option>
<option value="0.02">2%</option>
<option value="0.03">3%</option>
<option value="0.04">4%</option>
<option value="0.05">5%</option>
<option value="0.06">6%</option>
<option value="0.07">7%</option>
<option value="0.08">8%</option>
<option value="0.09">9%</option>
<option value="0.10">10%</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceDiscountAmount" id="LinePriceDiscountAmount">
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceWithDiscount" id="LinePriceWithDiscount">
</td>
<td>
<select type="number" name="TaxRate" id="TaxRate" onchange="calculate(this);"/>
<option value="0.00">Zero Rate</option>
<option value="0.20">Standard(20%)</option>
<option value="0.00">Exempt</option>
<option value="0.05">Reduced Rate</option>
<option value="0.00">Outside The Scope</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="TaxAmount" id="TaxAmount">
</td>
<td>
<input readonly="readonly" type="number" name="GrossOutput" id="GrossOutput">
</td>
</tr>
</table>
</form>
</body>
</html>
The issue was, whenever you were hitting calculate function, it was taking values from first row only as there was no different ids for each rows. Here I used this to differentiate each row.
I had to use parentNode twice. If you find a cleaner version, please do share.
Also, using jQuery will make things easier.
I have this form working almost perfect. If I apply discount to default price is changes, if I apply taxes it autofills too. But the last field with the sum of price after discount plus taxes is not working. Any idea?
Here is the code and a Fiddle
<html>
<body>
<table width="339" border="0" cellpadding="0">
<tr>
<td width="98">Taxes</td>
<td width="115">Discount</td>
<td width="118">Default price</td>
</tr>
<tr>
<td><select class="select" name="taxes" onChange="updateInput()">
<option value="no" selected>no taxes</option>
<option value="19">19% taxes</option> <!-- <====================== -->
</select></td>
<td><select class="select" name="discount" onChange="updateInput()">
<option value="0" selected>0% discount</option>
<option value="5">5% discount</option>
<option value="10">10% discount</option>
<option value="20">20% discount</option>
</select></td>
<td><input type="text" class="input140" name="cost" id="cost" value="1000"></td>
</tr>
<tr>
<td>Price after discount</td>
<td>Taxes</td>
<td>Total Price to pay</td>
</tr>
<tr>
<td><input type="text" name="price" value="1000"></td>
<td><input type="text" name="ttaxes" value="0"></td> <!-- <====================== -->
<td><input type="text" name="total" value="0"></td>
</tr>
</table>
<script type="text/javascript">
function updateInput(){
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
var taxes = document.getElementsByName("taxes")[0].value; // <======================
if ( isNaN( taxes ) ) // IF "no taxes" IS SELECTED...
document.getElementsByName("ttaxes")[0].value = 0;
else { cost = document.getElementsByName("price")[0].value;
document.getElementsByName("ttaxes")[0].value = (cost * (taxes / 100));
}
}
</script>
</body>
</html>
The Fiddle DEMO
https://jsfiddle.net/nte6xqdv/7/
I need the last field Total to pay to sum "Price after discount Taxes" automaticly but is not working
Thanks a lot
You may find it easier to identify the issues you are having if you separate out each part of the process.
If you store all of the elements you are going to be using at the beginning you will make your calculations easier to read plus avoid unnecessary DOM calls.
/**
* Elements
*/
var taxes = document.getElementsByName('taxes')[0];
var discount = document.getElementsByName('discount')[0];
var cost = document.getElementsByName('cost')[0];
var price = document.getElementsByName('price')[0];
var ttaxes = document.getElementsByName('ttaxes')[0];
var total = document.getElementsByName('total')[0];
/**
* Calculations
*/
function updateInput() {
price.value = cost.value - (cost.value * (discount.value / 100));
ttaxes.value = (price.value * (taxes.value / 100));
var sum = parseFloat(price.value) + parseFloat(ttaxes.value);
total.value = sum.toFixed(2);
}
/**
* Event Listeners
*/
taxes.addEventListener('change', updateInput);
discount.addEventListener('change', updateInput);
cost.addEventListener('change', updateInput);
cost.addEventListener('keyup', updateInput);
<table width="339" border="0" cellpadding="0">
<tr>
<td width="98">Taxes</td>
<td width="115">Discount</td>
<td width="118">Default price</td>
</tr>
<tr>
<td>
<select name="taxes" class="select">
<option value="0" selected>no taxes</option>
<option value="19">19% taxes</option>
</select>
</td>
<td>
<select name="discount" class="select">
<option value="0" selected>0% discount</option>
<option value="5">5% discount</option>
<option value="10">10% discount</option>
<option value="20">20% discount</option>
</select>
</td>
<td>
<input type="text" name="cost" class="input140" value="1000">
</td>
</tr>
<tr>
<td>Price after discount</td>
<td>Taxes</td>
<td>Total Price to pay</td>
</tr>
<tr>
<td><input type="text" name="price" value="1000"></td>
<td><input type="text" name="ttaxes" value="0"></td>
<td><input type="text" name="total" value="0"></td>
</tr>
</table>
I guess your problem is that two input are string, and you used + operator to concatenate them. It should be converted to a number to do add operation.
var total = document.getElementsByName("total")[0];
total.value = parseFloat(document.getElementsByName("price")[0].value) +
parseFloat(document.getElementsByName("ttaxes")[0].value);
https://jsfiddle.net/ssk7833/nte6xqdv/8/
function updateInput(){
var total = document.getElementsByName("total")[0];
var taxes = document.getElementsByName("ttaxes")[0].value;
var price = document.getElementsByName("price")[0].value;
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
var taxes = document.getElementsByName("taxes")[0].value; // <======================
if ( isNaN( taxes ) ) // IF "no taxes" IS SELECTED...
document.getElementsByName("ttaxes")[0].value = 0;
else { cost = document.getElementsByName("price")[0].value;
document.getElementsByName("ttaxes")[0].value = parseInt(cost * (taxes / 100));
}
total.value = parseInt(taxes * 10) + parseInt(price) || parseInt(price); //No NaNs
}
call updateInput whenever the input changes uses jQuery... jQuery is very simple to use, and learn, and every JavaScript programmer should know how to use it.
In jquery... invoke the change callback:
$("#inputFieldIdHere").change(updateInput())
What will this do?
This will do several things. It will:
Wait until the input field has changed whatever is inside
When the contents of the input field changes it will call the function: updateInput()
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));
})
});