Jquery Form Calculation not aligning - javascript

I have trying to get this jQuery math to work with my form which I got the snippet to work fine but when transferring across to the required form I can't get it aligned to run the math required.
any pointers to where I am going wrong.
<script type="text/javascript" src="jquery-1.12.3.js"></script>
<script>
jQuery(function($) {
$(".Qty1, .TradePrice1").change(function() {
var total = 0;
$(".Qty1").each(function() {
var self = $(this),
TradePrice1 = self.next(".TradePrice1"),
subtotal = parseInt(self.val(), 10) * parseFloat(TradePrice1.val(), 10);
total += (subtotal || 0);
});
$("#total1").val(total);
});
});
</script>
<tr>
<th><div align="center">
<input type='text' name='F01u1' id='F01u1' />
</th>
<td>
<input type='text' name='Model1' id='Model1' />
</td>
<td>
<input type='text' name='Description1' id='Description1' />
</td>
<td>
<input type="text" name='TradePrice1' id='TradePrice1' />
</td>
<th>
<input type="text" name='Qty1' id='Qty1' />
</th>
<td>
<input type='text' name='Total1' id='Total1' />
</div></td>
</tr>

You have quite a few issues in your code.
the inputs will have duplicate id attributes which is invalid. You should use classes instead
you have some extraneous div elements which aside from being not needed, aren't opened or closed properly.
parseFloat() only takes a single parameter
the total field is not readonly so it can be amended by anyone, to any value desired.
your code works out the total for all rows and places it at the end of each individual row
.TradePrice1 is not a sibling of .Qty1 hence it will never be found from a next() call
With all that in mind you can massively improve your code. Try this:
$(".qty, .tradeprice").change(function() {
var total = 0;
$(".qty").each(function() {
var $qty = $(this),
$row = $qty.closest('tr'),
$tradePrice = $row.find('.tradeprice'),
$subtotal = $row.find('.subtotal');
subtotal = parseInt($qty.val(), 10) * parseFloat($tradePrice.val());
total += subtotal;
$subtotal.val(subtotal);
});
$('.total').val(total);
}).change();
input {
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>
<input type='text' name='F01u1' class='F01u1' />
</th>
<td>
<input type='text' name='Model' class='model' />
</td>
<td>
<input type='text' name='Description' class='description' />
</td>
<td>
<input type="text" name='TradePrice' class='tradeprice' value="100" />
</td>
<th>
<input type="text" name='Qty' class='qty' value="2" />
</th>
<td>
<input type='text' name='Total' class='subtotal' readonly="true" />
</td>
</tr>
<tr>
<th>
<input type='text' name='F01u1' class='F01u1' />
</th>
<td>
<input type='text' name='Model' class='model' />
</td>
<td>
<input type='text' name='Description' class='description' />
</td>
<td>
<input type="text" name='TradePrice' class='tradeprice' value="123" />
</td>
<th>
<input type="text" name='Qty' class='qty' value="5" />
</th>
<td>
<input type='text' name='Total' class='subtotal' readonly="true" />
</td>
</tr>
<tr>
<td colspan="6" align="right">
Total:
<input type='text' name='Total' class='total' readonly="true" />
</td>
</tr>
</table>
Note that the default values are purely for demonstration purposes and can be removed if needed.

Related

Trying to figure out problem with table value calculator

I'm having some trouble on a HTML and JS practice project I'm working on, in where the following function is meant to calculate the total expense cost for the user. The program gave me an error for the date[i], which I then defined as one set of the td elements of the table (which the dates were listed under using the debugger). However, it then gave me another issue with a different function, stating that:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '.[object HTMLTableCellElement]' is not a valid selector.
I worry that I'm running in circles for this, and I would like to know what I'm doing wrong. Any help with this would be appreciated.
Pastebin with full code: https://pastebin.com/My3xzyS4
Code most relevant:
function calcClass(sumClass) {
var sumFields = document.querySelectorAll("." + sumClass); //this is the one giving me issues
var sumTotal = 0;
for (var i = 0; i < sumFields.length; i++) {
var itemValue = parseFloat(sumFields[i].value);
if(!isNaN(itemValue)) {
sumTotal += itemValue;
}
}
return sumTotal;
}
function calcExp() {
var expTable = document.querySelectorAll("table#travelExp tr");
for (var i = 0; i < expTable.length; i++) {
var date = document.querySelectorAll("table#travelExp td");
document.getElementById("subtotal"+ [i]).value = formatNumber(calcClass(date[i]), 2);
}
document.getElementById("transTotal").value = formatNumber(calcClass(trans), 2);
document.getElementById("lodgeTotal").value = formatNumber(calcClass(lodge), 2);
document.getElementById("mealTotal").value = formatNumber(calcClass(meal), 2);
document.getElementById("otherTotal").value = formatNumber(calcClass(other), 2);
document.getElementById("expTotal").value = formatUSCurrency(calcClass(sum));
}
function formatNumber(val, decimals) {
return val.toLocaleString(undefined, {minimumFractionDigits: decimals,
maximumFractionDigits: decimals});
}
function formatUSCurrency(val) {
return val.toLocaleString('en-US', {style: "currency", currency: "USD"} );
I see the way you are doing the sums: horizontal, per date, and vertical, per item. Now, your calcClass function takes a class name as input, which is a string. Instead, what you are passing every time is a variable. In the first instance the variable is actually an object. Hence the error: an object cannot be used as a query selector.
Why is it an object?
Why is that an object? Because the last time you used date, it was as a variable to hold the result of document.querySelectorAll("table#travelExp td") which returns a list of objects.
Now, you have a similar problem in the next calls you do to calcClass.
Fix
The fix is actually pretty easy, given the way you have already cleverly structured your table: simply make those strings, as they are meant to be. So, something like this should work.
function calcExp() {
var expTable = document.querySelectorAll("table#travelExp tr");
for (var i = 0; i < expTable.length; i++) {
// var date = document.querySelectorAll("table#travelExp td"); // likely not needed
document.getElementById("subtotal" + i).value = formatNumber(calcClass('date' + i), 2);
}
document.getElementById("transTotal").value = formatNumber(calcClass('trans'), 2);
document.getElementById("lodgeTotal").value = formatNumber(calcClass('lodge'), 2);
document.getElementById("mealTotal").value = formatNumber(calcClass('meal'), 2);
document.getElementById("otherTotal").value = formatNumber(calcClass('other'), 2);
document.getElementById("expTotal").value = formatUSCurrency(calcClass('sum'));
}
The reason you have the error is that you're putting an element from querySelectorAll but your calcClass function receives a string argument and query again with querySelectorAll. It seems like you need to pass 'date'+[i] to calcClass and let the function partial(daily) sum of each costs.
After that, I've countered another error "<a class='gotoLine' href='#352:54'>352:54</a> Uncaught TypeError: Cannot set property 'value' of null". You're iterating expTable.length times but only has 6 rows. I put 6 directly to the for loop and you need to replace this number.
"use strict";
/*
New Perspectives on HTML5, CSS3, and JavaScript 6th Edition
Tutorial 13
Case Problem 2
Author: 4terrabytes
Date: 7/27/2020
Filename: dl_expenses.js
Function List
=============
validateSummary()
Validates the data entry in the summary field.
calcClass(sumClass)
Sums up all of the data values for elements of the sumClass class.
calcExp()
Calculates the travel expenses from all categories and dates.
formatNumber(val, decimals)
Formats the value, "val" to the number of decimals indicated
by "decimals", adding thousands separators.
formatUSCurrency(val)
Formats the value, "val", as U.S. currency.
*/
//create an anon function
window.addEventListener("load", function() {
var changingCells = document.querySelectorAll("table#travelExp input.sum");
for(var i = 0; i < changingCells.length; i++) {
changingCells[i].onchange = calcExp;
}
document.getElementById("submitButton").onclick = validateSummary;
});
function validateSummary(){
var summary = document.getElementById("summary");
if (summary.validity.valueMissing) {
summary.setCustomValidity("You must include a summary of the trip in your report.");
}
else {
summary.setCustomValidity("");
}
}
function calcClass(sumClass) {
var sumFields = document.querySelectorAll("." + sumClass);
var sumTotal = 0;
for (var i = 0; i < sumFields.length; i++) {
var itemValue = parseFloat(sumFields[i].value);
if(!isNaN(itemValue)) {
sumTotal += itemValue;
}
}
return sumTotal;
}
function calcExp() {
var expTable = document.querySelectorAll("table#travelExp input.sum");
for (var i = 0; i < 6; i++) {
var date = document.querySelectorAll("table#travelExp td");
document.getElementById("subtotal"+ [i]).value = formatNumber(calcClass("date"+[i]), 2);
}
document.getElementById("transTotal").value = formatNumber(calcClass("trans"), 2);
document.getElementById("lodgeTotal").value = formatNumber(calcClass("lodge"), 2);
document.getElementById("mealTotal").value = formatNumber(calcClass("meal"), 2);
document.getElementById("otherTotal").value = formatNumber(calcClass("other"), 2);
document.getElementById("expTotal").value = formatUSCurrency(calcClass("sum"));
}
function formatNumber(val, decimals) {
return val.toLocaleString(undefined, {minimumFractionDigits: decimals,
maximumFractionDigits: decimals});
}
function formatUSCurrency(val) {
return val.toLocaleString('en-US', {style: "currency", currency: "USD"} );
}
//HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<!--
New Perspectives on HTML5, CSS3, and JavaScript 6th Edition
Tutorial 13
Case Problem 2
Travel Expense Report
Author: 4terrabytes
Date: 7/27/2020
Filename: dl_expense.html
-->
<title>DeLong Enterprises Expense Report</title>
<meta charset="utf-8" />
<link href="dl_base.css" rel="stylesheet" />
<link href="dl_layout.css" rel="stylesheet" />
<script src="dl_expense.js" async></script>
</head>
<body>
<header>
<nav class="horizontal">
<ul>
<li>Home</li>
<li>Policies</li>
<li>Reports</li>
<li>Employment</li>
<li>Financial</li>
<li>Insurance</li>
<li>Accounts</li>
</ul>
</nav>
<img src="dl_logo.png" alt="DeLong Enterprises" id="logoImg" />
</header>
<section>
<form name="expReport" id="expReport" method="post" action="dl_valid.html">
<table id="travelSummary">
<tr>
<th>Trip Summary<span>*</span></th>
</tr>
<tr>
<td>
<textarea id="summary" name="summary" required></textarea>
</td>
</tr>
</table>
<aside>
<h1>Expense Report</h1>
<p>Form: 2CEXP15<br />
* --- Required Field
</p>
<p>Send Report To:<br />
Debbie Larson<br />
Personnel Dept.<br />
Rm. 3801<br />
Ext. 1250
</p>
</aside>
<table id="empInfo">
<tr>
<th>Last Name<span>*</span></th>
<th>First Name<span>*</span></th>
<th>M.I.</th>
<th>Account<span>*</span></th>
<td><input type="text" name="accID" id="accID" pattern="^ACT\d{6}$" placeholder="ACTnnnnnn" required /></td>
</tr>
<tr>
<td><input type="text" name="lname" id="lname" required /></td>
<td><input type="text" name="fname" id="fname" required /></td>
<td><input type="text" name="init" id="init" required /></td>
<th>Department<span>*</span></th>
<td><input type="text" name="deptID" id="deptID" pattern="^DEPT\d{4,6}$" required placeholder="DEPTnnnnnn" /></td>
</tr>
<tr>
<th>Social Security Number<span>*</span></th>
<td colspan="2"><input type="text" name="ssn" id="ssn" pattern="^\d{3}-\d{2}-\d{4}$" required placeholder="nnn-nn-nnnn" /></td>
<th>Project<span>*</span></th>
<td><input type="text" name="projID" id="projID" pattern="^PROJ-[a-z]{2}-\d{3}$" required placeholder="PROJ-xx-ddd" /></td>
</tr>
</table>
<table id="travelExp">
<thead>
<tr>
<th>Travel Date</th>
<th>Air & Trans</th>
<th>Lodging</th>
<th>Meals & Tips</th>
<th>Other</th>
<th>TOTAL</th>
</tr>
</thead>
<tfoot>
<tr>
<th>SUMMARY</th>
<td><input type="text" name="transTotal" id="transTotal" readonly /></td>
<td><input type="text" name="lodgeTotal" id="lodgeTotal" readonly /></td>
<td><input type="text" name="mealTotal" id="mealTotal" readonly /></td>
<td><input type="text" name="otherTotal" id="otherTotal" readonly /></td>
<td><input type="text" name="expTotal" id="expTotal" readonly /></td>
</tr>
</tfoot>
<tbody>
<tr>
<td>
<input type="date" name="tDate0" id="tDate0" class="tDate" />
</td>
<td>
<input type="text" name="trans0" id="trans0" class="trans date0 sum" />
</td>
<td>
<input type="text" name="lodge0" id="lodg0" class="lodge date0 sum" />
</td>
<td>
<input type="text" name="meal0" id="meal0" class="meal date0 sum" />
</td>
<td>
<input type="text" name="other0" id="other0" class="other date0 sum" />
</td>
<td>
<input type="text" name="subtotal0" id="subtotal0" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate1" id="tDate1" class="tDate" />
</td>
<td>
<input type="text" name="trans1" id="trans1" class="trans date1 sum" />
</td>
<td>
<input type="text" name="lodge1" id="lodg1" class="lodge date1 sum" />
</td>
<td>
<input type="text" name="meal1" id="meal1" class="meal date1 sum" />
</td>
<td>
<input type="text" name="other1" id="other1" class="other date1 sum" />
</td>
<td>
<input type="text" name="subtotal1" id="subtotal1" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate2" id="tDate2" class="tDate" />
</td>
<td>
<input type="text" name="trans2" id="trans2" class="trans date2 sum" />
</td>
<td>
<input type="text" name="lodge2" id="lodg2" class="lodge date2 sum" />
</td>
<td>
<input type="text" name="meal2" id="meal2" class="meal date2 sum" />
</td>
<td>
<input type="text" name="other2" id="other2" class="other date2 sum" />
</td>
<td>
<input type="text" name="subtotal2" id="subtotal2" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate3" id="tDate3" class="tDate" />
</td>
<td>
<input type="text" name="trans3" id="trans3" class="trans date3 sum" />
</td>
<td>
<input type="text" name="lodge3" id="lodg3" class="lodge date3 sum" />
</td>
<td>
<input type="text" name="meal3" id="meal3" class="meal date3 sum" />
</td>
<td>
<input type="text" name="other3" id="other3" class="other date3 sum" />
</td>
<td>
<input type="text" name="subtotal3" id="subtotal3" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate4" id="tDate4" class="tDate" />
</td>
<td>
<input type="text" name="trans4" id="trans4" class="trans date4 sum" />
</td>
<td>
<input type="text" name="lodge4" id="lodg4" class="lodge date4 sum" />
</td>
<td>
<input type="text" name="meal4" id="meal4" class="meal date4 sum" />
</td>
<td>
<input type="text" name="other4" id="other4" class="other date4 sum" />
</td>
<td>
<input type="text" name="subtotal4" id="subtotal4" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate5" id="tDate5" class="tDate" />
</td>
<td>
<input type="text" name="trans5" id="trans5" class="trans date5 sum" />
</td>
<td>
<input type="text" name="lodge5" id="lodg5" class="lodge date5 sum" />
</td>
<td>
<input type="text" name="meal5" id="meal5" class="meal date5 sum" />
</td>
<td>
<input type="text" name="other5" id="other5" class="other date5 sum" />
</td>
<td>
<input type="text" name="subtotal5" id="subtotal5" class="subtotal" readonly />
</td>
</tr>
</tbody>
</table>
<input id="submitButton" type="submit" value="Submit Report" />
</form>
</section>
<footer>
<nav class="vertical">
<ul>
<li>Travel Expenses</li>
<li>Information Change</li>
<li>Time Off Request</li>
<li>Paystubs</li>
<li>Health Insurance</li>
<li>Forms/Requests</li>
<li>Team Contacts</li>
<li>Reimbursements</li>
<li>Grievances</li>
<li>Staff Directory</li>
</ul>
</nav>
<p>DeLong Enterprises © 2018 All Rights Reserved</p>
</footer>
</body>
</html>

How to get input value (without ID) from table

I have an input tag on table :
example :
<table border="1" id="datatable">
<thead>
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type='text' name="a[]" value="a1">
</td>
<td>
<input type='text' name="b[]" value="b1">
</td>
<td>
<input type='text' name="b[]" value="c1">
</td>
</tr>
<tr>
<td>
<input type='text' name="a[]" value="a2">
</td>
<td>
<input type='text' name="b[]" value="b2">
</td>
<td>
<input type='text' name="c[]" value="c2">
</td>
</tr>
</tbody>
I want to get value from input using javascript.
I have try :
var x = document.getElementById("datatable").rows[1].cells;
alert(x[1].innerHTML);
but the result is :
<input type='text' value="a">
please help. thank you
This is invalid html. Each input element should have a name attribute this is how the forms data is submitted. Then you could use value=document.querySelector("input[name='fred']").value;
Edit
Since you are using brackets (and therefore sending back array value with same name) you will need to use:
// create array for values
a_s_array = [];
// get input values
a_s = document.querySelectorAll("input[name='a[]']");
// loop through elements
for( var x=0; x<a_s.length; x++ ) {
// store input value into array
a_s_array.push( a_s[x].value );
}
Try this:-
var x = document.getElementById("datatable").rows[1].cells;
alert(x[0].children[0].value);
You can try this jquery code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<table border="1" id="datatable">
<thead>
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type='text' name="a[]" value="a1">
</td>
<td>
<input type='text' name="b[]" value="b1">
</td>
<td>
<input type='text' name="b[]" value="c1">
</td>
</tr>
<tr>
<td>
<input type='text' name="a[]" value="a2">
</td>
<td>
<input type='text' name="b[]" value="b2">
</td>
<td>
<input type='text' name="c[]" value="c2">
</td>
</tr>
</tbody>
<script>
$(document).ready(function(){
var td = $("#datatable").find('td');
$.each(td, function() {
alert($(this).find('input[type="text"]').val());
});
});
</script>
</body>
</html>

Submitting Dynamic Form Fields to mysql via PHP

I have created a dynamic form and I am trying to send the form data to mysql through PHP but its not working. Data is not getting sent even from the very first row without adding a dynamic row. I'm new to this topic, so I'm out of ideas to solve it. How can I make this form a correct one and send accurate data to mysql?
In my form I have 3 fields that are not dynamic.
Here is the form code:
<form name="newbillform" method="POST" action="save_purchase_details.php">
<table style=" border:1px solid black" cellpadding="5px" cellspacing="0px" align="center" border="0">
<tr>
<td colspan="4" style="background:#0066FF; color:#FFFFFF; fontsize:20px" align="center">
ADD NEW PURCHASE RECORD
</td>
</tr>
<tr>
<td>Date:</td>
<td>
<input type="date" name="p_date"/>
</td>
</tr>
<tr>
<td>Invoice Number:</td>
<td>
<input type="text" name="invoice_no" size="50">
</td>
</tr>
<tr>
<td>Balance:</td>
<td>
<input type="text" name="balance" size="50">
</td>
</tr>
</table>
<h2 style="padding-left:10px;">Enter Product Details Below:-</h2>
<table id="product_details" style="margin-top:8px;" align='center' border='1' width="900px">
<tr id="row1">
<td>
<input type="text" name="qty[]" value="" placeholder="Quantity" size="6">
</td>
<td>
<input type="text" name="pack[]" value="" placeholder="Pack" size="6">
</td>
<td>
<input type="text" name="item_name[]" value="" placeholder="Item Name" size="16">
</td>
<td>
<input type="text" name="batch[]" value="" placeholder="Batch" size="6">
</td>
<td>
<input type="text" name="expiry[]" value="" placeholder="Expiry" size="6">
</td>
<td>
<input type="text" name="mrp[]" value="" placeholder="M.R.P" size="6">
</td>
<td>
<input type="text" name="rate[]" value="" placeholder="Rate" size="6">
</td>
<td>
<input type="text" name="vat[]" value="" placeholder="VAT" size="6">
</td>
<td>
<input type="text" name="discount[]" value="" placeholder="Discount" size="6">
</td>
<td>
<input type="button" class="button-add-row" onclick="add_row();" value="ADD ROW" size="8">
</td>
</tr>
</table>
<center>
<input type="submit" name="submit_row" value="SUBMIT">
</center>
</form>
Here is the javascript code:
<script type="text/javascript">
function add_row()
{
$rowno = $("#product_details tr").length;
$rowno = $rowno + 1;
$("#product_details tr:last").after("<tr id='row"+$rowno+"'><td><input type='text' name='qty[]' placeholder='Quantity' size='6'></td><td><input type='text' name='pack[]' placeholder='Pack' size='6'></td><td><input type='text' placeholder='Item Name' name='item_name[]' size='16'></td><td><input type='text' name='batch[]' placeholder='Batch' size='6'></td><td><input type='text' name='expiry[]' placeholder='Expiry' size='6'></td><td><input type='text' name='mrp[]' placeholder='M.R.P' size='6'></td><td><input type='text' name='rate[]' placeholder='Rate' size='6'></td><td><input type='text' name='vat[]' placeholder='VAT' size='6'></td><td><input type='text' name='discount[]' placeholder='Discount' size='6'></td><td><input type='button' class='button-add-row' value='DELETE' onclick=delete_row('row"+$rowno+"')></td></tr>");
}
function delete_row(rowno)
{
$('#'+rowno).remove();
}
</script>
Here is the PHP code:
<?php
$connect = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("store_records",$connect) or die(mysql_error());
if(isset($_POST['submit_row']))
{
$amount;
$grand_total;
for($i = 0; $i < count($_POST['item_name']); $i++)
{
$qty = $_POST['qty'][$i];
$p_date = $_POST['p_date'];
$invoice_no = $_POST['invoice_no'];
$balance = $_POST['balance'];
$pack = $_POST['pack'][$i];
$item_name = $_POST['item_name'][$i];
$batch = $_POST['batch'][$i];
$expiry = $_POST['expiry'][$i];
$mrp = $_POST['mrp'][$i];
$rate = $_POST['rate'][$i];
$vat = $_POST['vat'][$i];
$discount = $_POST['discount'][$i];
$amount = $balance+($qty*$rate)-$discount;
$grand_total = $amount+(($amount*$vat)/100);
$query =mysql_query("insert into bill_records values('', '$p_date', '$invoice_no', '$balance', '$qty','$pack','$item_name', '$batch', '$expiry', '$mrp', '$rate', '$vat', '$discount', '$amount', '$grand_total')");
}
}
?>
It would be of great help. Thank You..

How to get the column sum total values of last 2 column's in this dynamic table

The below code is used to add new row to the table, also multiply two fields and show the result in the final field, in this dynamically generated row and at last part of code, removes the added row if it is not needed.
<script type="text/javascript">
$(window).load(function(){
$('.add-box').click(function() {
var box_html = $('<tr class="multLote"><td align="center"><input type="text" name="lote[]" value="0" style="width:15%;font-weight:bold;" /></td> ' +
'<td><textarea name="lote100[]" value="0" style="height:25px;font-size:10pt;width:60;font-weight:bold;" class="val100" > </textarea></td>' +
'<td><input type="text" name="lote20[]" value="0" class="val20" /></td>' +
'<td><input type="text" name="lote10[]" value="0" class="val10" /></td>' +
'<td><input type="text" disabled name="lote_result[]" class="lote_result" value="0"></td>' +
'<th>Remover</th></tr>');
$('#tabela-lotes tbody').append(box_html);
return false;
});
$('#tabela-lotes').on("keyup", ".multLote input", function() {
var mult = 0;
// for each row:
console.log($(this).closest('table').find("tr.multLote").length);
$(this).closest('tr.multLote').each(function() {
// get the values from this row:
var $val20 = $('.val20', this).val();
var $val10 = $('.val10', this).val();
console.log($val100);
var $total = ($val20 * $val10);
console.log($total);
// set total for the row
$('.lote_result', this).val($total);
mult += $total;
});
});
$('#tabela-lotes').on('click', '.remove-box', function(e) {
e.preventDefault();
$(this).closest('tr.multLote').remove();
});
});
</script>
This is the html code.
<form action="tabledb.php" method="POST">
<body>
<input type="button" class="add-box" value="Add">
<table id="tabela-lotes">
<thead>
<tr>
<th>
SL. NO
</th>
<th>
PRODUCT NAME
</th>
<th>
RATE PER CB
</th>
<th>
CBs
</th>
<th>
AMOUNT
</th>
</tr>
</thead>
<tbody><tr class="multLote">
<td align="center">
<input type="text" name="lote[]" value="0" style="width:15%;font-weight:bold;">
</td>
<td>
<textarea name="lote100[]" style="height:25px;font-size:10pt;width:60;font-weight:bold;" class="val100" value="0"> </textarea>
</td>
<td>
<input type="text" name="lote20[]" class="val20" value="0">
</td>
<td>
<input type="text" name="lote10[]" class="val10" value="0">
</td>
<td>
<input type="text" disabled="" name="lote_result[]" class="lote_result" value="0">
</td>
</tr>
</tbody></table>
<table>
<tr><th>
Total CBS :</th>
<td> <input type="text" name="total_cbs" id="total_cbs" placeholder="Total CBS" style="height:25px;font-weight:bold;" onfocus="cal1()" readonly ></td></tr>
<tr><th>Total AMOUNT : </th>
<td><input type="text" name="total" id="total" placeholder="Total Rs." style="height:25px;font-weight:bold;" onfocus="cal2('.$i.')" readonly></td></tr>
</table>
<input type="submit" value="submit">
</form>
I want to the get the total coloumn sum of lote10[ ] and lote_result[ ] fields to be displayed in the total_cbs and total fields respectively.Please help, Thank you in advance.
enter image description here
I have updated my question with the image of the output, which states exactly what i need, Thank You.
Assuming the end result looks like this:
var result = 0;
var elements = document.getElementsByTagName("table")[0].getElementsByTagName("tr");
for (var i = elements.length - 1; i > elements.length - 3; i--) {
var inputs = elements[i].getElementsByTagName('input');
result += parseInt(inputs[inputs.length - 1].value);
}
console.log('total', result);
alert('total ' + result);
<table>
<tbody>
<tr class="multLote">
<td align="center">
<input type="text" name="lote[]" value="0" style="width:15%;font-weight:bold;">
</td>
<td>
<textarea name="lote100[]" value="0" style="height:25px;font-size:10pt;width:60;font-weight:bold;" class="val100"></textarea>
</td>
<td>
<input type="text" name="lote20[]" value="0" class="val20">
</td>
<td>
<input type="text" name="lote10[]" value="0" class="val10">
</td>
<td>
<input type="text" disabled="" name="lote_result[]" class="lote_result" value="7">
</td>
<th>Remover
</th>
</tr>
<tr class="multLote">
<td align="center">
<input type="text" name="lote[]" value="0" style="width:15%;font-weight:bold;">
</td>
<td>
<textarea name="lote100[]" value="0" style="height:25px;font-size:10pt;width:60;font-weight:bold;" class="val100"></textarea>
</td>
<td>
<input type="text" name="lote20[]" value="0" class="val20">
</td>
<td>
<input type="text" name="lote10[]" value="0" class="val10">
</td>
<td>
<input type="text" disabled="" name="lote_result[]" class="lote_result" value="7">
</td>
<th>Remover
</th>
</tr>
<tr class="multLote">
<td align="center">
<input type="text" name="lote[]" value="0" style="width:15%;font-weight:bold;">
</td>
<td>
<textarea name="lote100[]" value="0" style="height:25px;font-size:10pt;width:60;font-weight:bold;" class="val100"></textarea>
</td>
<td>
<input type="text" name="lote20[]" value="0" class="val20">
</td>
<td>
<input type="text" name="lote10[]" value="0" class="val10">
</td>
<td>
<input type="text" disabled="" name="lote_result[]" class="lote_result" value="7">
</td>
<th>Remover
</th>
</tr>
<tr class="multLote">
<td align="center">
<input type="text" name="lote[]" value="0" style="width:15%;font-weight:bold;">
</td>
<td>
<textarea name="lote100[]" value="0" style="height:25px;font-size:10pt;width:60;font-weight:bold;" class="val100"></textarea>
</td>
<td>
<input type="text" name="lote20[]" value="0" class="val20">
</td>
<td>
<input type="text" name="lote10[]" value="0" class="val10">
</td>
<td>
<input type="text" disabled="" name="lote_result[]" class="lote_result" value="7">
</td>
<th>Remover
</th>
</tr>
<tr class="multLote">
<td align="center">
<input type="text" name="lote[]" value="0" style="width:15%;font-weight:bold;">
</td>
<td>
<textarea name="lote100[]" value="0" style="height:25px;font-size:10pt;width:60;font-weight:bold;" class="val100"></textarea>
</td>
<td>
<input type="text" name="lote20[]" value="0" class="val20">
</td>
<td>
<input type="text" name="lote10[]" value="0" class="val10">
</td>
<td>
<input type="text" disabled="" name="lote_result[]" class="lote_result" value="7">
</td>
<th>Remover
</th>
</tr>
</tbody>
</table>
JSFIDDLE

Validation using Jquery of only checked rows of a multi row HTML table

Given the following HTML table which is part of a form on a PHP page, what is the best practice for validating user input?
If a user checks a checkbox for a row (or multiple rows), what is the best way to ensure the StartDate and EndDate input fields have data using client side scripting.
I would like to use jquery but I am very new to jquery. Would the jquery validation plugin make the most sense?
<table width='100%' border='0' cellspacing='0' cellpadding='0'>
<tr>
<td>
<input type='checkbox' id='Product[916109]' name='Product[916109]' value='916109' class='select'>
</td>
<td>
<input type='text' id='ProductName[916109]' name='ProductName[916109]' value='ESY792'>
</td>
<td>
<input type='text' id='StartDate[916109]' name='StartDate[916109]' class='startDatePicker'>
</td>
<td>
<input type='text' id='EndDate[916109]' name='EndDate[916109]' class='endDatePicker'>
</td>
</tr>
<tr>
<td>
<input type='checkbox' id='Product[916110]' name='Product[916110]' value='916110' class='select'>
</td>
<td>
<input type='text' id='ProductName[916110]' name='ProductName[916110]' value='ESY793'>
</td>
<td>
<input type='text' id='StartDate[916110]' name='StartDate[916110]' class='startDatePicker'>
</td>
<td>
<input type='text' id='EndDate[916110]' name='EndDate[916110]' class='endDatePicker'>
</td>
</tr>
<tr>
<td>
<input type='checkbox' id='Product[916111]' name='Product[916111]' value='916111' class='select'>
</td>
<td>
<input type='text' id='ProductName[916111]' name='ProductName[916111]' value='ESY794'>
</td>
<td>
<input type='text' id='StartDate[916111]' name='StartDate[916111]' class='startDatePicker'>
</td>
<td>
<input type='text' id='EndDate[916111]' name='EndDate[916111]' class='endDatePicker'>
</td>
</tr>
<tr>
<td>
<input type='checkbox' id='Product[916112]' name='Product[916112]' value='916112' class='select'>
</td>
<td>
<input type='text' id='ProductName[916112]' name='ProductName[916112]' value='ESY795'>
</td>
<td>
<input type='text' id='StartDate[916112]' name='StartDate[916112]' class='startDatePicker'>
</td>
<td>
<input type='text' id='EndDate[916112]' name='EndDate[916112]' class='endDatePicker'>
</td>
</tr>
<tr>
<td>
<input type='submit' id='btnSubmit' name='btnSubmit' value='Submit'>
</td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
This should do the trick for the use case you've described:
var theForm = $('form'),
rows = theForm.find('tr');
theForm.on('submit', function(evt) {
rows.each(function(i, row) {
var valid = row.find( '.select' ).is( ':checked' )
&& ( row.find('.startDatePicker').val() && row.find('.endDatePicker').val() )
if ( !valid ) return evt.preventDefault();
} );
} );
No sense loading the validation plugin if that's all you need it for, but if you're likely to use it elsewhere then go for it.

Categories

Resources