I am trying to make a table that can make a +, x, H and in different colors and then on click it draws on the table. Could anyone help me out? I don't expect you to write the full code but if you could maybe provide some advice and/or example code I would totally appreciate it!
<!HTML>
<html>
<head>
<title>JScript</title>
<script language="javascript">
function Design()
{
}
</script>
</head>
<body>
<table border="1px" cellpadding="30px">
<tr><td name="h"></td><td></td><td></td><td></td><td name="h"></tr>
<tr><td></td><td></td><td name="h"></td><td></td><td></td></tr>
<tr><td></td><td></td><td name="h"></td><td></td><td></td></tr>
<tr><td></td><td></td><td name="h"></td><td></td><td></td></tr>
<tr><td name="h"></td><td></td><td></td><td></td><td name="h"></td></tr>
</table>
Pattern Choice: <br>
<input type="radio" name="sign" value="plus"> Plus Sign <br>
<input type="radio" name="sign" value="X"> Letter X <br>
<input type="radio" name="sign" value="H"> Letter H <br><br>
Color Choice: <br>
<select name="color" size="5">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="orange">Orange</option>
</select>
</div>
<br><br>
<input type="button" value="Color It" onclick="Design()">
<input type="reset" value="Clear">
</body>
</html>
I don't know if you can see but I the <td name="h"> I thought that would be the way to go to fill in each cell at least for H and then I was going to use multiple names if they overlapped if that's even possible?
I did this using javascript
<html>
<head>
function Design() {
var desgn;
if (document.getElementById('r1').checked) {
desgn = document.getElementById('r1').value;
}
if (document.getElementById('r2').checked) {
desgn = document.getElementById('r2').value;
}
if (document.getElementById('r3').checked) {
desgn = document.getElementById('r3').value;
}
console.log(desgn);
var e = document.getElementById("list");
var colr = e.options[e.selectedIndex].value;
var tabs = document.getElementById("tbl");
var rows = tabs.rows.length;
var trs = tabs.getElementsByTagName("tr")[0];
var tds = trs.cells
var colms = tds.length
var table = document.getElementById("tbl");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if (desgn == 'X') {
var y = rows - i - 1;
if (i == j || j == y) {
trs = tabs.getElementsByTagName("tr")[i];
trs.cells[j].style.backgroundColor = colr;
}
}
else if (desgn == 'plus') {
if (i == 2 || j == 2) {
trs = tabs.getElementsByTagName("tr")[i];
trs.cells[j].style.backgroundColor = colr;
}
}
else if (desgn == "H") {
if (j == 1 || j == 3 || i == 2 && j == 2) {
trs = tabs.getElementsByTagName("tr")[i];
trs.cells[j].style.backgroundColor = colr;
}
}
}
}
}
</script>
</head>
<body>
<table border="1px" cellpadding="30px" id="tbl">
<tr><td name="h"></td><td></td><td></td><td></td><td name="h"></tr>
<tr><td></td><td></td><td name="h"></td><td></td><td></td></tr>
<tr><td></td><td></td><td name="h"></td><td></td><td></td></tr>
<tr><td></td><td></td><td name="h"></td><td></td><td></td></tr>
<tr><td name="h"></td><td></td><td></td><td></td><td name="h"></td></tr>
</table>
Pattern Choice: <br>
<input id='r1' type="radio" name="sign" value="plus"> Plus Sign <br>
<input id='r2' type="radio" name="sign" value="X"> Letter X <br>
<input id='r3' type="radio" name="sign" value="H"> Letter H <br><br>
Color Choice: <br>
<select id='list' name="color" size="5">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="orange">Orange</option>
</select>
</div>
<br><br>
<input type="button" value="Color It" onclick="Design()">
<input type="reset" value="Clear" >
</body>
</html>
I did this using jquery
function Design() {
var desgn = $('body input[type=radio]:checked').val();
var colr = $('body select option:selected').text();
var MyRows = $('table').find('tr');
var MyCells = $('table').find('tr').find('td');
var MyColm = MyCells.length / MyRows.length
for (var i = 0; i < MyRows.length; i++) {
for (var j = 0; j < MyColm; j++) {
if (desgn == 'X') {
var x = MyRows.length;
var y = x - i - 1;
if (i == j || j == y)
$('body table tr:eq(' + i + ') td:eq(' + j + ')').css('background-color', colr);
}
else if (desgn == 'plus') {
if(i==2||j==2)
$('body table tr:eq(' + i + ') td:eq(' + j + ')').css('background-color', colr);
}
else if(desgn=="H") {
if (j == 1 || j == 3 ||i==2 && j==2)
$('body table tr:eq(' + i + ') td:eq(' + j + ')').css('background-color', colr);
}
}
}
}
</script>
</head>
<body>
<table border="1px" cellpadding="30px">
<tr><td name="h"></td><td></td><td></td><td></td><td name="h"></tr>
<tr><td></td><td></td><td name="h"></td><td></td><td></td></tr>
<tr><td></td><td></td><td name="h"></td><td></td><td></td></tr>
<tr><td></td><td></td><td name="h"></td><td></td><td></td></tr>
<tr><td name="h"></td><td></td><td></td><td></td><td name="h"></td></tr>
</table>
Pattern Choice: <br>
<input type="radio" name="sign" value="plus"> Plus Sign <br>
<input type="radio" name="sign" value="X"> Letter X <br>
<input type="radio" name="sign" value="H"> Letter H <br><br>
Color Choice: <br>
<select name="color" size="5">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="orange">Orange</option>
</select>
</div>
<br><br>
<input type="button" value="Color It" onclick="Design()">
<input type="reset" value="Clear" onclick="clearall()">
</body>
</html>
You can have it this way
HTML
<table id="transactions_table_name" class="table project-table table-centered table-nowrap">
<thead>
<tr>
<th scope="col">Transaction Type</th>
<th scope="col">Code</th>
<th scope="col">Previous balance</th>
<th scope="col">Amount</th>
<th scope="col">Last Balance</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JAVASCRIPT
for (let i = 0; i < transactions.length; i++) {
var transaction = transactions[i];
$("<tr><th scope='row'>" + transaction.type + "</th><td>" + transaction.code +
"</td><td>" + transaction.previousBalance + "</td><td>" + transaction.amount +
"</td><td> " + transaction.lastBalance + "</td><td>" + transaction.date + "
</td></tr>").appendTo("#transactions_table_name");
}
Credits to http://dotnetwithsqlserver.blogspot.com/2016/11/how-to-manipulate-and-fill-html-table.html
Related
I have a table that a user can dynamically add a row as needed. I need to add a text box underneath the table that will dynamically output the total of the last column using JavaScript. If the calculations can't be done dynamically then I can add a calculate button underneath the text box
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 4) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = 'row_'+rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems= row.querySelectorAll("input, select");
for (i=0; i<listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
}
} else {
alert("Maximum Passenger per ticket is 4.");
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll('[name=qty]')[0].value;
var myBox3 = mainRow.querySelectorAll('[name^=sel]')[0].value;
var total = mainRow.querySelectorAll('[name=total]')[0];
var myResult1 = myBox1 * myBox3;
total.value = myResult1;
}
</SCRIPT>
</HEAD>
<BODY>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<table id="dataTable" class="form" border="1">
<tbody>
<tr id='row_0'>
<p>
<td>
<label>Quantity</label>
<input type="number" required="required" name="qty" oninput="calculate('row_0')">
</td>
<td>
<label for="sel">Price</label>
<select name="sel" id="sel" oninput="calculate('row_0')" required>
<option value="" disabled selected>Choose your option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<label for="total">Total</label>
<input type="text" required="required" class="small" name="total">
</td>
</p>
</tr>
</tbody>
</table>
</BODY>
</HTML>
Any help will be greatly appreciated.
Here try this.
I added the sum in a tfoot first but the way you added new row made it awkward so I just put it in a div at the bottom of the table.
<html>
<head>
<title>Add/Remove dynamic rows in HTML table</title>
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 4) {
// limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = "row_" + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.querySelectorAll("input, select");
for (i = 0; i < listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('" + row.id + "')");
}
} else {
alert("Maximum Passenger per ticket is 4.");
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll("[name=qty]")[0].value;
var myBox3 = mainRow.querySelectorAll("[name^=sel]")[0].value;
var total = mainRow.querySelectorAll("[name=total]")[0];
var myResult1 = myBox1 * myBox3;
total.value = myResult1;
// calculate the totale of every total
var sumContainer = document.getElementById("totalOfTotals");
var totalContainers = document.querySelectorAll("[name=total]"),
i;
var sumValue = 0;
for (i = 0; i < totalContainers.length; ++i) {
sumValue += parseInt(totalContainers[i].value);
}
sumContainer.textContent = sumValue;
}
</script>
</head>
<body>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<table id="dataTable" class="form" border="1">
<tbody>
<tr id="row_0">
<p>
<td>
<label>Quantity</label>
<input
type="number"
required="required"
name="qty"
oninput="calculate('row_0')"
/>
</td>
<td>
<label for="sel">Price</label>
<select name="sel" id="sel" oninput="calculate('row_0')" required>
<option value="" disabled selected>Choose your option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<label for="total">Total</label>
<input
type="text"
required="required"
class="small"
name="total"
/>
</td>
</p>
</tr>
</tbody>
</table>
<div>
<tr>
<span>Sum</span>
<span id="totalOfTotals">0</span>
</tr>
</div>
</body>
</html>
I believe you want to get a total value of last column throughout the table.
Then I think you need to Iterate through column.
Using below function code.
function totalvalues() {
var table = document.getElementById("dataTable");
var totalcellvalue = 0;
for (var i = 0, row; row = table.rows[i]; i++) {
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//columns would be accessed using the "col" variable assigned in the for loop
if (j == 2) {
//alert('col html>>'+col.children[1].value);
totalcellvalue += parseInt(col.children[1].value);
}
}
}
console.log(totalcellvalue);
}
// And I have called the above method ```totalvalues()`` in your ```calculate()``` method.
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 4) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = 'row_' + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.querySelectorAll("input, select");
for (i = 0; i < listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('" + row.id + "')");
}
} else {
alert("Maximum Passenger per ticket is 4.");
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll('[name=qty]')[0].value;
var myBox3 = mainRow.querySelectorAll('[name^=sel]')[0].value;
var total = mainRow.querySelectorAll('[name=total]')[0];
var myResult1 = myBox1 * myBox3;
total.value = myResult1;
totalvalues();// calling my function here
}
</SCRIPT>
</HEAD>
<BODY>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<table id="dataTable" class="form" border="1">
<tbody>
<tr id='row_0'>
<p>
<td>
<label>Quantity</label>
<input type="number" required="required" name="qty" oninput="calculate('row_0')">
</td>
<td>
<label for="sel">Price</label>
<select name="sel" id="sel" oninput="calculate('row_0')" required>
<option value="" disabled selected>Choose your option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<label for="total">Total</label>
<input type="number" required="required" class="small" name="total">
</td>
</p>
</tr>
</tbody>
</table>
</BODY>
</HTML>
I need to prevent users from adding Duplicate values to a HTML Table based on the Month mentioned in the table when click add row Button. I tried with Following method, but it will always skip the first row when checking duplicate values. Image shows the error I'm getting with Duplicates.
Method I tried.
<select id="month" class="form-control">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option value="March">March</option>
<option value="April">April</option>
</select>
<input type="number" id="amt5" />
<input type="button" class="btn" value="Add Row" onclick="ftm2add5()">
<table id="table5" class="table table-dark" border="1">
<thead>
<tr>
<th scope="col">Select</th>
<th scope="col">Month</th>
<th scope="col">T/O Value</th>
<th scope="col" style="display:none;">TORef</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
function ftm2add5() {
var cat = $("#month").val();
var amt = $("#amt5").val();
var cate = $("#month option:selected").html();
if (amt == "") {
$("#amt5").addClass("red-border");
} else {
var allCells = $("#table5 tr td:nth-child(2)");
var textMapping = {};
allCells.each(function() {
textMapping[$(this).text()] = true;
});
var count = 0;
for (var text in textMapping) count++;
if (count !== allCells.length) {
alert("found duplicate values");
} else {
var markup =
"<tr><td><input type='checkbox' name='record'></td><td>" +
cate +
"</td><td style='display:none;'>" +
cat +
"</td><td>" +
amt +
"</td></tr>";
$("#table5 tbody").append(markup);
}
}
}
Simply with a jquery selector:
$('#table5 tr:contains("' + cat +'")').length
function ftm2add5() {
var cat = $("#month").val();
var amt = $("#amt5").val();
var cate = $("#month option:selected").html();
if (amt == "") {
$("#amt5").addClass("red-border");
} else {
if ($('#table5 tr:contains("' + cat +'")').length > 0) {
alert("found duplicate values");
} else {
var markup =
"<tr><td><input type='checkbox' name='record'></td><td>" +
cate +
"</td><td style='display:none;'>" +
cat +
"</td><td>" +
amt +
"</td></tr>";
$("#table5 tbody").append(markup);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="month" class="form-control">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option value="March">March</option>
<option value="April">April</option>
</select>
<input type="number" id="amt5" />
<input type="button" class="btn" value="Add Row" onclick="ftm2add5()">
<table id="table5" class="table table-dark" border="1">
<thead>
<tr>
<th scope="col">Select</th>
<th scope="col">Month</th>
<th scope="col">T/O Value</th>
<th scope="col" style="display:none;">TORef</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
Hi guys can someone help me about my problem. The problem is when I put a value on the Buy Price and Tax rate column it didn't show the result on the sell price input box.
This my function
$(document).ready(function(){
function final_total(count){
var final_product_amount = 0;
for(j=1;j<=count;j++){
var quantity = 0;
var buy_price = 0;
var sell_price = 0;
var tax_rate = 0;
var total_amount = 0;
var total_sell = 0;
var actual_amount = 0;
var total_tax = 0;
var min_qty = 0;
quantity = $('#quantity'+j).val();
if(quantity>0){
buy_price = $('#buy_price'+j).val().replace(",","");
if(buy_price > 0 ){
total_amount = parseFloat(quantity) * parseFloat(buy_price);
$('#total_amount'+j).val('P '+total_amount);
tax_rate = $('#tax_rate'+j).val();
if(tax_rate>0){
total_sell = parseFloat(buy_price) * parseFloat(tax_rate)/100;
total_tax = parseFloat(buy_price) + parseFloat(total_sell);
$('#sell_price'+j).val('P '+total_tax);
}
}
actual_amount = $('#total_amount'+j).val().replace("P ","");
final_product_amount = parseFloat(final_product_amount) + parseFloat(actual_amount);
}
}
$('#final_total_amount').text('₱ '+final_product_amount);
}
}
I tried modifying the code but it did not show when I finished inputting some value on tax rate. When I clicked the + button and filling the input filled, the sell price on the first row is being filled and working. It only works when new table row is filled. Hope someone can help me about this one. Thanks.
Use onblur function to calculate selling price on both textbox buy_price and tax_rate.
onblur jquery api.
Below code snippet is to show how you can utilize the onblur function to calculate selling price and grand total amount.
function calculateSellPrice(_i) {
var _buyPrice = $("#txtBuyPrice-" + _i).val();
var _tax = $("#txtTax-" + _i).val();
var _sellPrice = 0;
if(_buyPrice != "" && _tax != "") {
_sellPrice = parseFloat(_buyPrice) + parseFloat(_tax);
$("#txtSellPrice-" + _i).val(_sellPrice);
}
calculateTotal();
}
function calculateTotal() {
var count = 2;
var totalAmount = 0;
for(var j=1; j<=count; j++) {
var sellingPrice = $("#txtSellPrice-" + j).val();
if(sellingPrice != "")
totalAmount += parseFloat(sellingPrice);
}
$("#lblGrandTotal").text("Grand Total: " + totalAmount);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table class="table table-bordered">
<thead>
<tr>
<td>Sl.No</td>
<td>Product</td>
<td>Buy Price</td>
<td>Tax</td>
<td>Sell Price</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<select id="prod-1">
<option>Select</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
</select>
</td>
<td>
<input type="text" id="txtBuyPrice-1" value="" placeholder="Buy Price" onblur="calculateSellPrice(1);" />
</td>
<td>
<input type="text" id="txtTax-1" value="" placeholder="Tax" onblur="calculateSellPrice(1);" />
</td>
<td>
<input type="text" id="txtSellPrice-1" value="" placeholder="Sell Price" disabled />
</td>
</tr>
<tr>
<td>2</td>
<td>
<select id="prod-2">
<option>Select</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
</select>
</td>
<td>
<input type="text" id="txtBuyPrice-2" value="" placeholder="Buy Price" onblur="calculateSellPrice(2);" />
</td>
<td>
<input type="text" id="txtTax-2" value="" placeholder="Tax" onblur="calculateSellPrice(2);" />
</td>
<td>
<input type="text" id="txtSellPrice-2" value="" placeholder="Sell Price" disabled />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: right;">
<label id="lblGrandTotal">Grand Total: 0</label>
</td>
</tr>
</tfoot>
</table>
</body>
</html>
I cannot figure out how to make this code just calculate the amount column the addrow and deleterow functions work just can figure out who to get this to calculate the total amount on the amount column.
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '#ncItems.add', function() {
var row = $(this).parents('tr');
var clone = row.clone();
// clear the values
var tr = clone.closest('tr');
tr.find('input[type=text]').val('');
$(this).closest('tr').after(clone);
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" + total +".00");
});
$(document).on("blur", ".last", function() {
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" +total+".00");
document.getElementById("ntotal").value ="$" +total+".00";
});
$(document).on('focus', ".last", function() {
var $qty = $(this).parents("tr").find("input[name^='quantity']");
var $pr = $(this).parents("tr").find("input[name^='price']");
var $amnt = $(this).parents("tr").find("input[name^='amount']");
var a = 0;
if ($qty.val() == '' || $pr.val() == '') {
console.log("No values found.");
return false;
} else {
console.log("Converting: ", $qty.val(), $pr.val());
var q = parseInt($qty.val());
var p = parseFloat($pr.val());
console.log("Values found: ", q, p);
}
a = q * p;
$amnt.val(Math.round(a * 100) / 100);
});
$(document).on('click', 'ncItems .removeRow', function() {
if ($('#ncItems .add').length > 1) {
$(this).closest('tr').remove();
}
});
});
</script>
<div id="dvncc">
<form id="ncc">
<table id="ncItems" name="ncItems" align="center">
<tr>
<th>Type</th>
<th>Discription</th>
<th>Amount</th>
<th>Actions</th>
</tr>
<tr>
<td>
<select name="type[]" class="next" required>
<option value=" selected="selected"">Please Select..</option>
<option value="Code">Code</option>
<option value="Regular">Regular</option>
</select>
</td>
<input type="text" name="discription[]" class="next" required />
</td>
<td>
<input type="text" name="amount[]" class="next last" required readonly/>
</td>
<td>
<input type="button" name="addRow[]" class="add" value='+' />
<input type="button" name="addRow[]" class="removeRow" value='-' />
</td>
</tr>
<tr>
<th>Total :</th>
<td id="nctotalPrice"></td>
</tr>
</table>
</form>
</div>
Please try this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Final</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.add', function() {
var row = $(this).parents('tr');
var clone = row.clone();
// clear the values
var tr = clone.closest('tr');
tr.find('input[type=text]').val('');
$(this).closest('tr').after(clone);
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" + total +".00");
});
$(document).on("blur", ".last", function() {
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" +total+".00");
document.getElementById("ntotal").value ="$" +total+".00";
});
$(document).on('focus', ".last", function() {
var $qty = $(this).parents("tr").find("input[name^='quantity']");
var $pr = $(this).parents("tr").find("input[name^='price']");
var $amnt = $(this).parents("tr").find("input[name^='amount']");
var a = 0;
if ($qty.val() == '' || $pr.val() == '') {
console.log("No values found.");
return false;
} else {
console.log("Converting: ", $qty.val(), $pr.val());
var q = parseInt($qty.val());
var p = parseFloat($pr.val());
console.log("Values found: ", q, p);
}
a = q * p;
$amnt.val(Math.round(a * 100) / 100);
});
$(document).on('click', '.removeRow', function() {
if ($('#ncItems .add').length > 1) {
$(this).closest('tr').remove();
}
});
});
</script>
</head>
<body>
<div id="dvncc">
<form id="ncc">
<table id="ncItems" name="ncItems" align="center">
<tr>
<th>Type</th>
<th>Discription</th>
<th>Amount</th>
<th>Actions</th>
</tr>
<tr>
<td>
<select name="type" class="next" required>
<option value="" selected="selected">Please Select..</option>
<option value="Code">Code</option>
<option value="Regular">Regular</option>
</select>
</td>
<td>
<input type="text" name="discription" class="next" required />
</td>
<td>
<input type="text" name="amount" class="next last" required/>
</td>
<td>
<input type="button" name="addRow" class="add" value='+' />
<input type="button" name="remove" class="removeRow" value='-' />
</td>
</tr>
<tr>
<th>Total :</th>
<td id="nctotalPrice"></td>
</tr>
</table>
</form>
</div>
</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.