How to create a function for Onkeyup - javascript

I am trying to write a function to analyze the users input before calling Onkeyup. I am not sure where to write this if statement, or if I have the correct syntax. I wrote the if statement inside the asset-tag class. This is my code:
const getAssetInfo = (assetTag, index) => {
// get the table row that this input is in
$.get("http://localhost:3000/assets/" + assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data);
})
.fail(() => {
// alert("DONE");
// console.log(index);
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
});
};
$('document').ready(() => {
// Handler to Add New Asset
const table = $("#formTable tbody");
let count = 1;
$('#add').click(() => {
const newRow = `
<tr index="${count}">
<form>
<td><input
class="asset-tag" id='asset_tag_no${count}' type='text'
if (input.length >= 4){
console.log('not enough characters to call API endpoint');
}
else{
onkeyup = "getAssetInfo(this.value,${count})";
}
bottom required /></td>
<td><input class="serial-no" id='manufacturer_serial_no${count}' type='text' bottom required readonly/></td>
<td><textarea class="description" id='description${count}' type='text' bottom required readonly description></textarea></td>
<td><input id='cost${count}' type='value' bottom require readonly/></td>
<td><input id='po_no${count}' type='text' bottom require readonly/></td>
<td><textarea id='remarks${count}' type='text' bottom remarks></textarea></td>
<td><button type="button" index="${count}" class="btn btn-danger btn-remove">X</button></td>
</form>
</tr>
`;
table.append(newRow);
// Handler to Remove New Asset
$('.btn-remove').click(function(){
let index = $(this).attr('index');
$(`tr[index='${index}'`).remove();
});
count++;
});
I want this error in the console log to only execute when a certain amount of characters are in the box instead of each time a character is inputted.

Related

User Input not found in Database error message

I am trying to set up an error message for the console to print when the user inputs a value not found in the database. I believe the syntax should be printed within the .fail(() => { section. I know my logic should be; if assetTag is not in the database, console.log an error message. The issue I have is it still prints the GET request with each valued typed. I believe the Onkeyup is also an issue. Here is a screenshot of the console:
How can I get the error message to always display Unable to locate ID in database once the user inputs the first key until something valid is found, eliminating the numerous GET requests? Here is my Javascript:
const getAssetInfo = (assetTag, index) => {
// get the table row that this input is in
$.get("http://localhost:3000/assets/" + assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data)
})
.fail(() => {
if (`#asset_tag_no` != assetTag ){
console.log('Unable to locate ID in database');
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
}
// });
else {
console.log('not enough characters to call API endpoint');
};
});
};
$('document').ready(() => {
// Handler to Add New Asset
const table = $("#formTable tbody");
let count = 1;
$('#add').click(() => {
const newRow = `
<tr index="${count}">
<form>
<td><input
class="asset-tag" id='asset_tag_no${count}' type='text'
onkeyup = "getAssetInfo(this.value,${count})";
bottom required /></td>
<td><input class="serial-no" id='manufacturer_serial_no${count}' type='text' bottom required readonly/></td>
<td><textarea class="description" id='description${count}' type='text' bottom required readonly description></textarea></td>
<td><input id='cost${count}' type='value' bottom require readonly/></td>
<td><input id='po_no${count}' type='text' bottom require readonly/></td>
<td><textarea id='remarks${count}' type='text' bottom remarks></textarea></td>
<td><button type="button" index="${count}" class="btn btn-danger btn-remove">X</button></td>
</form>
</tr>
`;
table.append(newRow);
// Handler to Remove New Asset
$('.btn-remove').click(function(){
let index = $(this).attr('index');
$(`tr[index='${index}'`).remove();
});
count++;
});

Onkeyup to fire a get request after only a few charcters

I am using Onkeyup to fire when a user inputs a certain ID into the search box. One problem I am trying to fix is having the function run only after 4 or more characters are in the submission box. For example, the ID number 0949 is fired when the user types out each digit, returning a GET request error each time when it should only fire at the end of the 4 digit submission. Here is a screenshot from the console log:
Ive tried including a .length to my onkeyup function as well as a fail catch to try but nothing works and it still fires after every single input. Here is my JavaScript code:
const getAssetInfo = (assetTag, index) => {
// get the table row that this input is in
$.get("http://localhost:3000/assets/" + assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data);
})
.fail(() => {
// alert("DONE");
// console.log(index);
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
}); };
$('document').ready(() => {
// Handler to Add New Asset
const table = $("#formTable tbody");
let count = 1;
$('#add').click(() => {
const newRow = `
<tr index="${count}">
<form>
<td><input class="asset-tag" id='asset_tag_no${count}' type='text'
onkeyup = "getAssetInfo(this.value,${count})";
bottom required /></td>
<td><input class="serial-no" id='manufacturer_serial_no${count}' type='text' bottom required readonly/></td>
<td><textarea class="description" id='description${count}' type='text' bottom required readonly description></textarea></td>
<td><input id='cost${count}' type='value' bottom require readonly/></td>
<td><input id='po_no${count}' type='text' bottom require readonly/></td>
<td><textarea id='remarks${count}' type='text' bottom remarks></textarea></td>
<td><button type="button" index="${count}" class="btn btn-danger btn-remove">X</button></td>
</form>
</tr>
`;
table.append(newRow);
// Handler to Remove New Asset
$('.btn-remove').click(function(){
let index = $(this).attr('index');
$(`tr[index='${index}'`).remove();
});
count++;
});
What is the most optimal way to ensure that only 4 or more digits can be entered into the search box, before it sends a GET request?
You should be able to wrap your getAssetInfo function with an if statement checking the amount of characters in the searchbar. Try rewriting the getAssetInfo function like this:
const getAssetInfo = (assetTag, index) => {
if (assetTag.length >= 4){
// get the table row that this input is in
$.get("http://localhost:3000/assets/" + assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data);
})
.fail(() => {
// alert("DONE");
// console.log(index);
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
});
} else {
console.log('not enough characters to call API endpoint');
}
};
In this if statement, I'm checking if the search bar has 4 or more characters before making the API call.

Error in updating field with dynamically generated row

I have inventory form to submit inventories to database. I'm facing an issue in updating unit cost and total cost of dynamically generated rows. As you can see in snapshots below. The name of products are fetching via autocomplete jQuery.
HTML CODE
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>Product Name/Code</th>
<th>Quantity</th>
<th>Unit Cost</th>
<th>Total Cost</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="p_scents">
<tr>
<td>1</td>
<td><input id="product_id" type="text" name="product_id[]" hidden><input id="product_code" type="text" name="product_code[]" hidden><input class="product_name form-control" id="product_name" type="text" placeholder="Type product name/code here" name="products[]" required></td>
<td><input class="quantity form-control" id="quantity" type="text" placeholder="Quantity to Buy" name="quantity[]" required /></td>
<td><div class="input-group"><span class="input-group-addon">$</span><input class="cost form-control" id="cost" placeholder="Unit Cost" type="text" readonly /></div></td>
<td><div class="input-group"><span class="input-group-addon">$</span><input class="total form-control" id="total" placeholder="Total" type="text" readonly /></div></td>
<td><button class="btn btn-default" type="button" id="addScnt"><i class="fa fa-plus "></i> Item</button></td>
</tr>
</tbody>
</table>
jQuery CODE
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type='text/javascript'>
jQuery(document).ready(function(){
var scntDiv = $('#p_scents');
var i = $('#p_scents tr').size() + 1;
$('#addScnt').click(function() {
scntDiv.append('<tr>'+
'<td>'+i+'</td>'+
'<td><input id="product_id" type="text" name="product_id[]" hidden><input id="product_code" type="text" name="product_code[]" hidden><input class="product_name form-control" id="product_name" type="text" placeholder="Type product name/code here" name="products[]" required></td>'+
'<td><input class="quantity form-control" id="quantity" type="text" placeholder="Quantity to Buy" name="quantity[]" required /></td>'+
'<td><div class="input-group"><span class="input-group-addon">$</span><input class="cost form-control" id="cost" placeholder="Unit Cost" type="text" readonly /></div></td>'+
'<td><div class="input-group"><span class="input-group-addon">$</span><input class="total form-control" id="total" placeholder="Total" type="text" readonly /></div></td>'+
'<td><a id="remScnt" class="btn btn-danger btn-xs"><span title="Delete" class="glyphicon glyphicon-remove"></span></a></td>'+
'</tr>');
i++;
//return false;
$('.product_name').autocomplete({
source:'http://localhost/Multi-Channel_Shipping/inc/auto_product.php',
minLength:2,
select:function(evt, ui)
{
// when a product is selected, populate related fields in this form
this.form.cost.value = ui.item.cost;
this.form.product_id.value = ui.item.product_id;
this.form.product_code.value = ui.item.product_code;
}
});
$('.quantity').keyup(function() {
updateTotal();
});
$('.cost').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseFloat($('.quantity').val());
var input2 = parseFloat($('.cost').val());
if (isNaN(input1) || isNaN(input2)) {
if(!input2){
$('.total').val($('.quantity').val());
}
if(!input1){
$('.total').val($('.cost').val());
}
} else {
$('.total').val(input1 * input2);
}
};
var output_total = $('.total');
var total = input1 + input2;
output_total.val(total);
});
//Remove button
$(document).on('click', '#remScnt', function() {
if (i > 2) {
$(this).closest('tr').remove();
i--;
}
return false;
});
$('.product_name').autocomplete({
source:'http://localhost/Multi-Channel_Shipping/inc/auto_product.php',
minLength:2,
select:function(evt, ui)
{
// when a zipcode is selected, populate related fields in this form
this.form.cost.value = ui.item.cost;
this.form.product_id.value = ui.item.product_id;
this.form.product_code.value = ui.item.product_code;
}
});
$('.quantity').keyup(function() {
updateTotal();
});
$('.cost').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseFloat($('.quantity').val());
var input2 = parseFloat($('.cost').val());
if (isNaN(input1) || isNaN(input2)) {
if(!input2){
$('.total').val($('.quantity').val());
}
if(!input1){
$('.total').val($('.cost').val());
}
} else {
$('.total').val(input1 * input2);
}
};
var output_total = $('.total');
var total = input1 + input2;
output_total.val(total);
});
</script>
AUTO_PRODUCT.PHP CODE
<?php
class DB
{
const DATABASE = 'multi-channel_shipping';
const HOST = 'localhost';
const USERNAME = 'root';
const PASSWORD = '';
static private $pdo;
static public function singleton()
{
if (!is_object(self::$pdo))
{
self::$pdo = new PDO('mysql:dbname=' . self::DATABASE . ';host=' . self::HOST,
self::USERNAME,
self::PASSWORD);
}
return self::$pdo;
}
private function __construct()
{
}
public function __clone()
{
throw new Exception('You may not clone the DB instance');
}
}
if (!isset($_REQUEST['term']))
{
die('([])');
}
$st = DB::singleton()
->prepare(
'SELECT * ' .
'FROM products ' .
'WHERE (name LIKE :name) OR (code LIKE :name) ' .
'ORDER BY name ASC ' .
'LIMIT 0,10');
$searchProduct = '%'.$_REQUEST['term'].'%';
$st->bindParam(':name', $searchProduct, PDO::PARAM_STR);
$data = array();
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
$data[] = array(
'value' => $row->code." - ".$row->name,
'cost' => $row->cost,
'product_id' => $row->id,
'product_code' => $row->code
);
}
}
echo json_encode($data);
flush();
?>
MySQL Data
--
-- Table structure for table `products`
--
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(100) NOT NULL,
`name` varchar(255) NOT NULL,
`unit` varchar(50) DEFAULT NULL,
`cost` decimal(25,2) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `code`, `name`, `unit`, `cost`) VALUES
(1, '4815162342', 'BAZIC 12 Dil Dil Pak', 'Packet', '0.10'),
(2, '23', 'Razer', 'Piece', '0.03');
I also need to put shipping cost input field and show grand total of invoice at bottom of table.
There a multiple issues with the page & code, so I will try to cover what I can. #Barmar also spotted additional issues so will try to cover everything and suggest some improvements.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/vx15mr4n/29/
Templating:
Rather than use text strings in code, it is easier to maintain HTML as HTML. The example I have provided uses a dummy script block (of type="text/template", which will be ignored by all browsers) but you can access the HTML content with $('#template').html().
Duplicate ID are invalid
You can't have duplicate IDs in a page. That is invalid HTML and jQuery will only see the first match. Use classes on the added elements instead and match on those.
so use:
<a class="remScnt"
and
$(document).on('click', '.remScnt', function()
Note: you will need to sort out any other duplicate IDs too (like product_id and quantity and cost and total). Your code already uses classes for those, so just move/delete the id attributes.
e.g. use classes for everything:
scntDiv.append('<tr>'+
'<td>'+i+'</td>'+
'<td><input class="product_id" type="text" name="product_id[]" hidden><input id="product_code" type="text" name="product_code[]" hidden><input class="product_name form-control" type="text" placeholder="Type product name/code here" name="products[]" required></td>'+
'<td><input class="quantity form-control" type="text" placeholder="Quantity to Buy" name="quantity[]" required /></td>'+
'<td><div class="input-group"><span class="input-group-addon">$</span><input class="cost form-control" placeholder="Unit Cost" type="text" readonly /></div></td>'+
'<td><div class="input-group"><span class="input-group-addon">$</span><input class="total form-control" placeholder="Total" type="text" readonly /></div></td>'+
'<td><a class="remScnt btn btn-danger btn-xs"><span title="Delete" class="glyphicon glyphicon-remove"></span></a></td>'+
'</tr>');
You are using a delegated event for one handler but not the others. You also need to add them for keyup (which can be combined as the code is the same):
$('#p_scents').on('keyup', '.quantity .cost', function() {
updateTotal();
});
IMPORTANT: Your code here is not matching a specific row. Also use #Barmar's fix like this to pass the current row:
$('#p_scents').on('keyup', '.quantity .cost', function() {
updateTotal($(this).closest('tr'));
});
Update: As Regent mentions below, you should not use document but use #p_scents for your delegated event handler:
$('#p_scents').on('click', '.remScnt', function()
A delegated event should be attached to the closest non-changing ancestor (if one is convenient/available). This will give a very small speed increase as it stops lower in the DOM.
I also cleaned up the event handler doing the calculations which now using temp vars, for elements relative to the row, and looks like:
// Update the row total of a specific row
var updateTotal = function ($row) {
// Get the specific inputs
var $quantity = $('.quantity', $row);
var $cost = $('.cost', $row);
var $total = $('.total', $row);
var input1 = parseFloat($quantity.val());
var input2 = parseFloat($cost.val());
if (isNaN(input1) || isNaN(input2)) {
if (!input2) {
$total.val($quantity.val());
}
if (!input1) {
$total.val($cost.val());
}
} else {
$total.val(input1 * input2);
}
var total = input1 * input2;
$total.val(total);
};
Note: Without the missing data, I cannot easily test the code, but you should get the idea.
Grand total
To update the grand total, you need to iterate all .total fields and add them to the shipping cost:
var updateGrandTotal = function()
{
// Now update the grand total
var grandTotal = 0;
$('.total').each(function () {
grandTotal += parseFloat($(this).val());
});
var shipping = parseFloat($('.shippingcost').val());
$('.grandtotal').val(grandTotal + shipping);
}
As you will want to update the grand total when the shipping changes, I refactored it out so it could also be called from a keyup on the shipping:
$('.shippingcost').keyup(function(){
updateGrandTotal();
});
The other issue is the autocomplete (which I could not test without a real data feed):
Basically get the select event to refer to the current field's row and find the appropriate fields to update:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/vx15mr4n/23/
select: function (evt, ui) {
// when a product is selected, populate related fields in this form
var $tr = $(this).closest("tr");
$(".cost",$tr).val(ui.item.cost);
$(".product_id", $tr).val(ui.item.product_id);
$(".product_code", $tr).val(ui.item.product_code);
}
When updateTotal() uses $('.quantity').val() it gets the value of the first field with that class, not the one in the row that the user was typing in. You need to pass the row to the function. Also, since the elements are added dynamically, you need to use delegation for the event bindings.
$('#p_scents').on('keyup', '.quantity, .cost', function() {
updateTotal($(this).closest('tr'));
});
var updateTotal = function (row) {
var input1 = parseFloat($('.quantity', row).val());
var input2 = parseFloat($('.cost', row).val());
if (isNaN(input1) || isNaN(input2)) {
if(!input2){
$('.total', row).val(input1);
}
if(!input1){
$('.total', row).val($(input2);
}
} else {
$('.total', row).val(input1 * input2);
}
}
var output_total = $('.total', row);
var total = input1 + input2;
output_total.val(total);
};

optimizing recursive getJSON method

Hi friends in my coding i'm using getJSON method to auto fill the text box when the user types the code in one text box, the description of the particular code will be displayed on the other textbox. I'm using more than 20 textboxes in my coding so the getJSON method has to be called 20 times, so i'm typing the code for 20 times is there is any other alternate way to optimize the code my is below .
function getCodeDetails1() {
$.getJSON("ieCodedetails.jsp", {
codeid: $("#txtIEcode1").val()
}, displayResult1);
}
function displayResult(data) {
if (data.error) { // emp not found
$("#txtIEdesc1").val(""); // clear fields
alert(data.error);
}
else { // Found employee. Display details
$("#txtIEdesc1").val(data.name);
}
}
function getCodeDetails2() {
$.getJSON("ieCodedetails.jsp", {
codeid: $("#txtIEcode2").val()
}, displayResult2);
}
function displayResult2(data) {
if (data.error) { // emp not found
$("#txtIEdesc2").val(""); // clear fields
alert(data.error);
}
else { // Found employee. Display details
$("#txtIEdesc2").val(data.name);
}
}
function getCodeDetails3() {
$.getJSON("ieCodedetails.jsp", {
codeid: $("#txtIEcode3").val()
}, displayResult3);
}
function displayResult3(data) {
if (data.error) { // emp not found
$("#txtIEdesc3").val(""); // clear fields
alert(data.error);
}
else { // Found employee. Display details
$("#txtIEdesc3").val(data.name);
}
}
<td><input type="text" name="txtIEcode1" id="txtIEcode1" onchange="getCodeDetails1()" style="width:60px;"></td>
<td><input type="text" id="txtIEdesc1" name="txtIEdesc1" style="width:220px;" readonly></td>
<td><input type="text" name="txtIEcode2" id="txtIEcode2" onchange="getCodeDetails2()" style="width:60px;"></td>
<td><input type="text" id="txtIEdesc2" name="txtIEdesc2" style="width:220px;" readonly></td>
<td><input type="text" name="txtIEcode3" id="txtIEcode3" onchange="getCodeDetails3()" style="width:60px;"></td>
<td><input type="text" id="txtIEdesc3" name="txtIEdesc1" style="width:220px;" readonly></td>
You could try to link your logic to some class instead of multiple ids:
<td><input type="text" name="txtIEcode1" class="txtIEcode" style="width:60px;"></td>
<td><input type="text" name="txtIEdesc1" class="txtIEdesc" style="width:220px;" readonly></td>
<td><input type="text" name="txtIEcode2" class="txtIEcode" style="width:60px;"></td>
<td><input type="text" name="txtIEdesc2" class="txtIEdesc" style="width:220px;" readonly></td>
<td><input type="text" name="txtIEcode3" class="txtIEcode" style="width:60px;"></td>
<td><input type="text" name="txtIEdesc3" class="txtIEdesc" style="width:220px;" readonly></td>
Then in your js:
$(".txtIEcode").each(function(i, el) {
var $el = $(el),
$desc = $el.parent().next('td').find(".txtIEdesc");
$el.on('change', function(){
$.getJSON("ieCodedetails.jsp", {
codeid: $el.val()
}, displayResult);
function displayResult(data) {
if (data.error) { // emp not found
$desc.val(""); // clear fields
alert(data.error);
}
else { // Found employee. Display details
$desc.val(data.name);
}
}
})
});
You have store the file name in variable and passed to arg
var pageName="ieCodedetails.jsp";
var textBoxId=$("#txtIEcode1");
getCodeDetails1(pageName,textBoxId);
function getCodeDetails1(pageName,textBoxId) {
$.getJSON(pageName, {
codeid: textBoxId.val()
}, displayResult1);
}

Dynamic form field extraction and calculation, how?

I have a form with variable length of dynamic field names, for instanced, item{n}, the n could be 1 or 30, and I need to calculate the subtotal of qty{n} * price{n} for each such data row, then finally sum subtotal up.
The form looks like the following:
<form>
<table name="forInstruction">
<tr><td>... </td> <td>...</td> ... more td </tr>
....
</table>
<table name="forUserinput">
<tr>
<td><input type="text" id="item1">,</td> <td><input type="text" id="qty1">,</td>
<td><input type="text" id="price1">,</td> <td>fieldX1 t1 </td> ... more td
</tr>
<tr>
<td><input type="text" id="item2">,</td> <td><input type="text" id="qty2">,</td>
<td><input type="text" id="price2">,</td> <td>fieldX2,t2 </td> ... more td
<td><input type="text" id="item3">,</td> <td><input type="text" id="qty3">,</td>
<td><input type="text" id="price3">,</td> <td>fieldX3,t3 </td> ... more td
...
</table>
<input type="button" value="Calculate subtotal and total" ... />
</form>
Notes:
a) t{n} = subtotal field.
b) as mentioned above, number of rows is unknown, it could be 1 to 30.
What I'd like to do is: calculate subtotal and total.
each subtotal = qty{n} * parseFloat(price{n})
My attempt is to loop through the entire form, I'm able to retrieve
all the values for the qty{n} field,
but I don't know how to retrieve the value of its Corresponding
Price{n}.
var fQ=0,fP=0;
st = 0;
total = 0;
for (f=0; f < document.qr.elements.length; f++) {
if (document.qr.elements[f].name.indexOf('qty')>=0) {
// alert(document.qr.elements[f].name + ' ' + document.qr.elements[f].value);
fQ = document.qr.elements[f].value;
// alert(fQ);
}
else if (document.qr.elements[f].name.indexOf('priceLabel')>=0) {
fP = document.qr.elements[f].value;
}
// what do we do here? Or this is not the good way to go?
}
Maybe, loop through the entire form isn't a good idea... only data rows in a named table? If so, how?
Many thanks in advance.
EDIT 1:
Upon advice,
new code:
var i = 0, t=0,
element;
while ((element = forms[0].elements['qty' + i])) {
var subtotal = forms[0].elements['qty' + i] * forms[0].elements['price' + i];
forms[0].elements['total' + i].value = subtotal;
t = t + parseFloat(subtotal);
alert(t);
// ...
i++;
}
forms[0].elements['totalFinal'].value = t;
but err msg:
"ReferenceError: forms is not defined". How come? Thanks.

Categories

Resources