Auto duplicate last row in table - javascript

I would like to duplicate the last row in a HTML table when the user types in any input inside the last row.
My code only works the first time it is run.
Maybe the table above it is being interfering with it? I also replaced :
if ( $(this).parents("tr").is("tr:last")) {
With
if ($(this).closest("tr").is(":last-child")) {
but this just causes a new row to be made on any input.
Var "t" might be off. I shrunk the size of the table and eyeballed the digits.
Javascript & Jquery
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById("Items").deleteRow(i);
}
function duperow() {
document.getElementById("LastRow").value = (Number($("tr:last td:first").text()) + 1);
var x = document.getElementById('Items');
var new_row = x.rows[1].cloneNode(true);
var len = (Number($("tr:last td:first").text()) + 1);
new_row.cells[0].innerHTML = len;
var inp = [];
for (t = 1; t < 4; t += 1) {
inp[t] = new_row.cells[t].querySelectorAll("input,select")[0];
inp[t].id += len;
inp[t].value = "";
}
inp[3].value = "0.00";
x.appendChild(new_row);
}
$(document).ready(function () {
$("input").keydown(function () {
if ( $(this).parents("tr").is("tr:last")) {
duperow();
}
});
});
HTML
<form id="test" action="submit.php" method="post" accept-charset="ISO-8859-1" enctype="multipart/form-data">
<table width="40%" class="alpha" cellpadding="6px" cellspacing="0" border="0" >
<tr>
<td>
<p>Supplier Name:</p><input name="suplname" type="text" id="suplname" name="suplname" size="10" maxlength="30" required/>
</td>
<td>
<p>Contact:</p><input name="contact" type="text" id="contact" name="contact" size="10" maxlength="40" />
</td>
</tr>
<tr>
<td colspan="2">
<p>Address:</p><input name="address" type="text" id="address" name="address" size="10" maxlength="30" />
</td>
<td>
<input style="display: none;" name="LastRow" type="hidden" id="LastRow" name="LastRow" size="4" maxlength="4" />
</td>
</tr>
</table>
<table class="beta" id="Items" border="1" width="50%" cellpadding="6px" cellspacing="0" border="0" >
<tr>
<th style="display: none;">ID</th>
<th>Acct#</th>
<th>Qty.</th>
<th>Price</th>
<th> </th>
<th> </th>
</tr>
<tr>
<td style="display: none;">1</td>
<td><select name="acct" id="acct" >
<option value=" " > </option>
<option value="1" >Thing</option>
<option value="2" >Thing2</option>
</select></td>
<td><input name="qty" type="number" id="qty" size="2" min="1" maxlength="6" required/></td>
<td><input name="price" type="number" id="price" min="0.00" step="0.01" value="0.00" style="width: 150px;"required/ onchange="total()"></td>
<td><input type="button" id="deleterowbtn" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addrowbtn" value="Add Item" onclick="duperow()"/></td>
</tr>
</table>
</table>
</form>

The issue is that you're binding to the keydown event listener on document.ready, which means that dynamically created input elements don't have anything bound to their keydown event.
You could do this instead:
$(document).ready(function () {
$("table.beta").on("keydown", "input", function (e) {
if ( $(e.target).parents("tr").is("tr:last")) {
duperow();
}
});
});

Related

How to Pass HTML Input values (batch) to Google Spreadsheet using only JavaScript?

I am using Google Scripts App, and I need to send the value of a batch of HTML Inputs to a Google Spreadsheet, on specific cells (row and column). However, the code I used, takes forever, and when it finish, not all inputs are passed to the Spreadsheet. Do to company restrictions (policies on software), I can only use pure JavaScript. This HTML page, is just a part of an App whit others pages, so using Google Forms, can’t be an option.
Is there a better way to send the inputs values to Google Spreadsheet faster and without skipping inputs?
I know that using too much “google.script.run”, slows down the process heavily, but can’t figure out another way. I am new at this, so don’t expect I know too much, just the barely basics.
Because of STACKOVERFLOW limitation, I limited the code to only three MODULES and 20 inputs per module (but there are four MODULES, with 30 inputs per module, as you can see it in the picture).
What alternative would you all recommend?
I am sharing the Code.gs and HTML scripts.
Thanks.
code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile("HTML_start_page")
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
return HtmlService.createHtmlOutputFromFile('HTML_start_page');
}
var ss = SpreadsheetApp.openByUrl("YOUR_GOOGLE_SPREADSHEET_URL_HERE");
var sheet_Balance = ss.getSheetByName("Page_1");
function getValuesFromForm_Balance_001A(id2000_01AA){
sheet_Balance.getRange(267,6).setValue(id2000_01AA);
}
function getValuesFromForm_Balance_002A(id2000_02AA){
sheet_Balance.getRange(268,6).setValue(id2000_02AA);
}
function getValuesFromForm_Balance_003A(id2000_03AA){
sheet_Balance.getRange(269,6).setValue(id2000_03AA);
}
function getValuesFromForm_Balance_004A(id2000_04AA){
sheet_Balance.getRange(270,6).setValue(id2000_04AA);
}
function getValuesFromForm_Balance_005A(id2000_05AA){
sheet_Balance.getRange(271,6).setValue(id2000_05AA);
}
function getValuesFromForm_Balance_006A(id1000_01AA){
sheet_Balance.getRange(272,6).setValue(id1000_01AA);
}
function getValuesFromForm_Balance_007A(id1000_02AA){
sheet_Balance.getRange(273,6).setValue(id1000_02AA);
}
function getValuesFromForm_Balance_008A(id1000_03AA){
sheet_Balance.getRange(274,6).setValue(id1000_03AA);
}
function getValuesFromForm_Balance_009A(id1000_04AA){
sheet_Balance.getRange(275,6).setValue(id1000_04AA);
}
function getValuesFromForm_Balance_010A(id1000_05AA){
sheet_Balance.getRange(276,6).setValue(id1000_05AA);
}
function getValuesFromForm_Balance_011A(id500_01AA){
sheet_Balance.getRange(277,6).setValue(id500_01AA);
}
function getValuesFromForm_Balance_012A(id500_02AA){
sheet_Balance.getRange(278,6).setValue(id500_02AA);
}
function getValuesFromForm_Balance_013A(id500_03AA){
sheet_Balance.getRange(279,6).setValue(id500_03AA);
}
function getValuesFromForm_Balance_014A(id500_04AA){
sheet_Balance.getRange(280,6).setValue(id500_04AA);
}
function getValuesFromForm_Balance_015A(id500_05AA){
sheet_Balance.getRange(281,6).setValue(id500_05AA);
}
function getValuesFromForm_Balance_016A(id200_01AA){
sheet_Balance.getRange(282,6).setValue(id200_01AA);
}
function getValuesFromForm_Balance_017A(id200_02AA){
sheet_Balance.getRange(283,6).setValue(id200_02AA);
}
function getValuesFromForm_Balance_018A(id200_03AA){
sheet_Balance.getRange(284,6).setValue(id200_03AA);
}
function getValuesFromForm_Balance_019A(id200_04AA){
sheet_Balance.getRange(285,6).setValue(id200_04AA);
}
function getValuesFromForm_Balance_020A(id200_05AA){
sheet_Balance.getRange(286,6).setValue(id200_05AA);
}
function getValuesFromForm_Balance_001B(id2000_01BB){
sheet_Balance.getRange(267,7).setValue(id2000_01BB);
}
function getValuesFromForm_Balance_002B(id2000_02BB){
sheet_Balance.getRange(268,7).setValue(id2000_02BB);
}
function getValuesFromForm_Balance_003B(id2000_03BB){
sheet_Balance.getRange(269,7).setValue(id2000_03BB);
}
function getValuesFromForm_Balance_004B(id2000_04BB){
sheet_Balance.getRange(270,7).setValue(id2000_04BB);
}
function getValuesFromForm_Balance_005B(id2000_05BB){
sheet_Balance.getRange(271,7).setValue(id2000_05BB);
}
function getValuesFromForm_Balance_006B(id1000_01BB){
sheet_Balance.getRange(272,7).setValue(id1000_01BB);
}
function getValuesFromForm_Balance_007B(id1000_02BB){
sheet_Balance.getRange(273,7).setValue(id1000_02BB);
}
function getValuesFromForm_Balance_008B(id1000_03BB){
sheet_Balance.getRange(274,7).setValue(id1000_03BB);
}
function getValuesFromForm_Balance_009B(id1000_04BB){
sheet_Balance.getRange(275,7).setValue(id1000_04BB);
}
function getValuesFromForm_Balance_010B(id1000_05BB){
sheet_Balance.getRange(276,7).setValue(id1000_05BB);
}
function getValuesFromForm_Balance_011B(id500_01BB){
sheet_Balance.getRange(277,7).setValue(id500_01BB);
}
function getValuesFromForm_Balance_012B(id500_02BB){
sheet_Balance.getRange(278,7).setValue(id500_02BB);
}
function getValuesFromForm_Balance_013B(id500_03BB){
sheet_Balance.getRange(279,7).setValue(id500_03BB);
}
function getValuesFromForm_Balance_014B(id500_04BB){
sheet_Balance.getRange(280,7).setValue(id500_04BB);
}
function getValuesFromForm_Balance_015B(id500_05BB){
sheet_Balance.getRange(281,7).setValue(id500_05BB);
}
function getValuesFromForm_Balance_016B(id200_01BB){
sheet_Balance.getRange(282,7).setValue(id200_01BB);
}
function getValuesFromForm_Balance_017B(id200_02BB){
sheet_Balance.getRange(283,7).setValue(id200_02BB);
}
function getValuesFromForm_Balance_018B(id200_03BB){
sheet_Balance.getRange(284,7).setValue(id200_03BB);
}
function getValuesFromForm_Balance_019B(id200_04BB){
sheet_Balance.getRange(285,7).setValue(id200_04BB);
}
function getValuesFromForm_Balance_020B(id200_05BB){
sheet_Balance.getRange(286,7).setValue(id200_05BB);
}
function getValuesFromForm_Balance_001C(id2000_01CC){
sheet_Balance.getRange(267,8).setValue(id2000_01CC);
}
function getValuesFromForm_Balance_002C(id2000_02CC){
sheet_Balance.getRange(268,8).setValue(id2000_02CC);
}
function getValuesFromForm_Balance_003C(id2000_03CC){
sheet_Balance.getRange(269,8).setValue(id2000_03CC);
}
function getValuesFromForm_Balance_004C(id2000_04CC){
sheet_Balance.getRange(270,8).setValue(id2000_04CC);
}
function getValuesFromForm_Balance_005C(id2000_05CC){
sheet_Balance.getRange(271,8).setValue(id2000_05CC);
}
function getValuesFromForm_Balance_006C(id1000_01CC){
sheet_Balance.getRange(272,8).setValue(id1000_01CC);
}
function getValuesFromForm_Balance_007C(id1000_02CC){
sheet_Balance.getRange(273,8).setValue(id1000_02CC);
}
function getValuesFromForm_Balance_008C(id1000_03CC){
sheet_Balance.getRange(274,8).setValue(id1000_03CC);
}
function getValuesFromForm_Balance_009C(id1000_04CC){
sheet_Balance.getRange(275,8).setValue(id1000_04CC);
}
function getValuesFromForm_Balance_010C(id1000_05CC){
sheet_Balance.getRange(276,8).setValue(id1000_05CC);
}
function getValuesFromForm_Balance_011C(id500_01CC){
sheet_Balance.getRange(277,8).setValue(id500_01CC);
}
function getValuesFromForm_Balance_012C(id500_02CC){
sheet_Balance.getRange(278,8).setValue(id500_02CC);
}
function getValuesFromForm_Balance_013C(id500_03CC){
sheet_Balance.getRange(279,8).setValue(id500_03CC);
}
function getValuesFromForm_Balance_014C(id500_04CC){
sheet_Balance.getRange(280,8).setValue(id500_04CC);
}
function getValuesFromForm_Balance_015C(id500_05CC){
sheet_Balance.getRange(281,8).setValue(id500_05CC);
}
function getValuesFromForm_Balance_016C(id200_01CC){
sheet_Balance.getRange(282,8).setValue(id200_01CC);
}
function getValuesFromForm_Balance_017C(id200_02CC){
sheet_Balance.getRange(283,8).setValue(id200_02CC);
}
function getValuesFromForm_Balance_018C(id200_03CC){
sheet_Balance.getRange(284,8).setValue(id200_03CC);
}
function getValuesFromForm_Balance_019C(id200_04CC){
sheet_Balance.getRange(285,8).setValue(id200_04CC);
}
function getValuesFromForm_Balance_020C(id200_05CC){
sheet_Balance.getRange(286,8).setValue(id200_05CC);
}
html
<!DOCTYPE html>
<html>
<body>
<!-- MODULE I ---->
<div>
<form style="border:0px solid #1f3f79; float:left; padding-left: 5px;">
<table>
<div>
<tr>
<tr>
<td>
<label>MODULE I</label>
<br>
<input type="text" value="0" id="id2000_01AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_02AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_03AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_04AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_05AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_01AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_02AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_03AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_04AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_05AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_01AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_02AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_03AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_04AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_05AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_01AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_02AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_03AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_04AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_05AA">
</td>
</tr>
</div>
</table>
</form>
</div>
<!-- MODULE II ---->
<div>
<form style="border:0px solid #1f3f79; float:left; padding-left: 5px;">
<table>
<div>
<tr>
<tr>
<td>
<label>MODULE II</label>
<br>
<input type="text" value="0" id="id2000_01BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_02BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_03BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_04BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_05BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_01BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_02BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_03BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_04BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_05BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_01BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_02BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_03BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_04BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_05BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_01BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_02BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_03BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_04BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_05BB">
</td>
</tr>
</div>
</table>
</form>
</div>
<!-- MODULE III ---->
<div>
<form style="border:0px solid #1f3f79; float:left; padding-left: 5px;">
<table>
<div>
<tr>
<tr>
<td>
<label>MODULE III</label>
<br>
<input type="text" value="0" id="id2000_01CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_02CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_03CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_04CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_05CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_01CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_02CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_03CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_04CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_05CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_01CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_02CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_03CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_04CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_05CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_01CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_02CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_03CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_04CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_05CC">
</td>
</tr>
</div>
</table>
</form>
</div>
<div>
<input type='button' id="botonREGISTRAR" value='REGISTER' onclick="get_New_Balances()">
</div>
<script>
function get_New_Balances() {
google.script.run.getValuesFromForm_Balance_001A(document.getElementById("id2000_01AA").value);
google.script.run.getValuesFromForm_Balance_002A(document.getElementById("id2000_02AA").value);
google.script.run.getValuesFromForm_Balance_003A(document.getElementById("id2000_03AA").value);
google.script.run.getValuesFromForm_Balance_004A(document.getElementById("id2000_04AA").value);
google.script.run.getValuesFromForm_Balance_005A(document.getElementById("id2000_05AA").value);
google.script.run.getValuesFromForm_Balance_006A(document.getElementById("id1000_01AA").value);
google.script.run.getValuesFromForm_Balance_007A(document.getElementById("id1000_02AA").value);
google.script.run.getValuesFromForm_Balance_008A(document.getElementById("id1000_03AA").value);
google.script.run.getValuesFromForm_Balance_009A(document.getElementById("id1000_04AA").value);
google.script.run.getValuesFromForm_Balance_010A(document.getElementById("id1000_05AA").value);
google.script.run.getValuesFromForm_Balance_011A(document.getElementById("id500_01AA").value);
google.script.run.getValuesFromForm_Balance_012A(document.getElementById("id500_02AA").value);
google.script.run.getValuesFromForm_Balance_013A(document.getElementById("id500_03AA").value);
google.script.run.getValuesFromForm_Balance_014A(document.getElementById("id500_04AA").value);
google.script.run.getValuesFromForm_Balance_015A(document.getElementById("id500_05AA").value);
google.script.run.getValuesFromForm_Balance_016A(document.getElementById("id200_01AA").value);
google.script.run.getValuesFromForm_Balance_017A(document.getElementById("id200_02AA").value);
google.script.run.getValuesFromForm_Balance_018A(document.getElementById("id200_03AA").value);
google.script.run.getValuesFromForm_Balance_019A(document.getElementById("id200_04AA").value);
google.script.run.getValuesFromForm_Balance_020A(document.getElementById("id200_05AA").value);
google.script.run.getValuesFromForm_Balance_001B(document.getElementById("id2000_01BB").value);
google.script.run.getValuesFromForm_Balance_002B(document.getElementById("id2000_02BB").value);
google.script.run.getValuesFromForm_Balance_003B(document.getElementById("id2000_03BB").value);
google.script.run.getValuesFromForm_Balance_004B(document.getElementById("id2000_04BB").value);
google.script.run.getValuesFromForm_Balance_005B(document.getElementById("id2000_05BB").value);
google.script.run.getValuesFromForm_Balance_006B(document.getElementById("id1000_01BB").value);
google.script.run.getValuesFromForm_Balance_007B(document.getElementById("id1000_02BB").value);
google.script.run.getValuesFromForm_Balance_008B(document.getElementById("id1000_03BB").value);
google.script.run.getValuesFromForm_Balance_009B(document.getElementById("id1000_04BB").value);
google.script.run.getValuesFromForm_Balance_010B(document.getElementById("id1000_05BB").value);
google.script.run.getValuesFromForm_Balance_011B(document.getElementById("id500_01BB").value);
google.script.run.getValuesFromForm_Balance_012B(document.getElementById("id500_02BB").value);
google.script.run.getValuesFromForm_Balance_013B(document.getElementById("id500_03BB").value);
google.script.run.getValuesFromForm_Balance_014B(document.getElementById("id500_04BB").value);
google.script.run.getValuesFromForm_Balance_015B(document.getElementById("id500_05BB").value);
google.script.run.getValuesFromForm_Balance_016B(document.getElementById("id200_01BB").value);
google.script.run.getValuesFromForm_Balance_017B(document.getElementById("id200_02BB").value);
google.script.run.getValuesFromForm_Balance_018B(document.getElementById("id200_03BB").value);
google.script.run.getValuesFromForm_Balance_019B(document.getElementById("id200_04BB").value);
google.script.run.getValuesFromForm_Balance_020B(document.getElementById("id200_05BB").value);
google.script.run.getValuesFromForm_Balance_001C(document.getElementById("id2000_01CC").value);
google.script.run.getValuesFromForm_Balance_002C(document.getElementById("id2000_02CC").value);
google.script.run.getValuesFromForm_Balance_003C(document.getElementById("id2000_03CC").value);
google.script.run.getValuesFromForm_Balance_004C(document.getElementById("id2000_04CC").value);
google.script.run.getValuesFromForm_Balance_005C(document.getElementById("id2000_05CC").value);
google.script.run.getValuesFromForm_Balance_006C(document.getElementById("id1000_01CC").value);
google.script.run.getValuesFromForm_Balance_007C(document.getElementById("id1000_02CC").value);
google.script.run.getValuesFromForm_Balance_008C(document.getElementById("id1000_03CC").value);
google.script.run.getValuesFromForm_Balance_009C(document.getElementById("id1000_04CC").value);
google.script.run.getValuesFromForm_Balance_010C(document.getElementById("id1000_05CC").value);
google.script.run.getValuesFromForm_Balance_011C(document.getElementById("id500_01CC").value);
google.script.run.getValuesFromForm_Balance_012C(document.getElementById("id500_02CC").value);
google.script.run.getValuesFromForm_Balance_013C(document.getElementById("id500_03CC").value);
google.script.run.getValuesFromForm_Balance_014C(document.getElementById("id500_04CC").value);
google.script.run.getValuesFromForm_Balance_015C(document.getElementById("id500_05CC").value);
google.script.run.getValuesFromForm_Balance_016C(document.getElementById("id200_01CC").value);
google.script.run.getValuesFromForm_Balance_017C(document.getElementById("id200_02CC").value);
google.script.run.getValuesFromForm_Balance_018C(document.getElementById("id200_03CC").value);
google.script.run.getValuesFromForm_Balance_019C(document.getElementById("id200_04CC").value);
google.script.run.getValuesFromForm_Balance_020C(document.getElementById("id200_05CC").value);
}
</script>
</body>
</html>
Here is the optimized and working code. Read the change logs below.
Code.gs:
function doGet() {
var template = HtmlService.createTemplateFromFile("HTML_start_page")
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getValuesFromForm(inputs){
var ss = SpreadsheetApp.openByUrl("spreadsheet url");
var sheet_Balance = ss.getSheetByName("Page_1");
// use setValues to write the 2D data by bulk
sheet_Balance.getRange(267, 7, inputs.length, inputs[0].length).setValues(inputs);
}
HTML_start_page.html:
<!DOCTYPE html>
<html>
<body>
<div>
<form style="border:0px solid #1f3f79; float:left; padding-left: 5px;">
<table id="table">
<tr>
<td><label>MODULE I</label></td>
<td><label>MODULE II</label></td>
<td><label>MODULE III</label></td>
<td><label>MODULE IV</label></td>
</tr>
</table>
</form>
</div>
<div>
<input type='button' id="botonREGISTRAR" value='REGISTER' onclick="get_New_Balances()">
</div>
<script>
window.onload = function () {
// automatically generate input rows
var table = document.getElementById("table");
var row, input, cell;
for (i = 0; i < 30; i++) {
row = table.insertRow();
for (j = 0; j < 4; j++) {
input = document.createElement('input')
input.type='text';
input.value='0';
cell = row.insertCell();
cell.appendChild(input);
}
}
};
function get_New_Balances() {
var tableRows = document.getElementById("table").rows;
var myrow, mytd;
var row = [], inputs = [];
for (i = 1; i < tableRows.length; i++) {
myrow = tableRows[i];
row = [];
for (j = 0; j < myrow.cells.length; j++) {
mytd = myrow.cells[j];
row.push(mytd.children[0].value);
}
inputs.push(row);
}
google.script.run.getValuesFromForm(inputs);
}
</script>
</body>
</html>
Change logs:
HTML table is now generated by a loop.
get_New_Balances now creates a 2D array from the table, and then passes it to the new function that writes 2D data directly to the sheet
getValuesFromForm is now using setValues to write the 2D data generated from the get_New_Balances
Input:
Output:
References:
Get the values of input field of each row of html table
Add and removing rows [with input field] in a table
About the same solution as #NaziA, without auto generation the HTML:
HTML:
...
<script>
function get_New_Balances() {
var nums1 = ['2000', '1000', '500', '200'];
var nums2 = ['01', '02', '03', '04', '05'];
var letters = ['AA', 'BB', 'CC'];
var values = [];
letters.forEach(letter => nums1.forEach(n1 => nums2.forEach(n2 => {
var id = 'id' + n1 + '_' + n2 + letter;
values.push(document.getElementById(id).value);
})));
var table = new Array(values.length / letters.length).fill('');
table = table.map((_, row) =>
letters.map((_, col) => values[row + table.length * col]));
google.script.run.main(table);
}
</script>
...
GS:
function doGet() {
var template = HtmlService.createTemplateFromFile("HTML_start_page");
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function main(table) {
var ss = SpreadsheetApp.openByUrl("URL");
var sheet_Balance = ss.getSheetByName("Page_1");
sheet_Balance.getRange(267,6,table.length,table[0].length).setValues(table);
}

Using a for loop and function to calculate row total on a table

I think this should be simple but just can't get it right...I am trying to get row total on a table that has incrementing ids like:
<table id="myTable" class="form">
<thead>
<tr>
....
</tr>
</thead>
<tbody>
<tr class="">
<td>
<input type="number" name="quantity" id="item-0-quantity">
</td>
<td>
<input type="number" name="unit_price"id="item-0-unit_price">
</td>
<td>
<td>
<input type="number" name="quantity" id="item-1-quantity">
</td>
<td>
<input type="number" name="unit_price"id="item-1-unit_price">
</td>
...etc
<td>
</tr>
</tbody>
</table>
I initially used the method below for each row's total calculation and it worked, but it's not efficient.
for first row: $('#item-0-quantity, #item-0-unit-price').on('input',function(e){
$('#Total').val(parseFloat($('#item-0-quantity').val()) * parseFloat($('#item-0-
unit-price').val()));
for second row: $('#item-1-quantity, #item-1-unit-price').on('input',function(e){
$('#Total').val(parseFloat($('#item-1-quantity').val()) * parseFloat($('#item-1-
unit-price').val()));
...and so on.
I thought i would better to use a For Loop to iterate and update the value of i based on a rowCounter like:
var rowCounter = $("#myTable tr").length - 1;
for (var i = 0; i <= rowCounter; i++) {
$('#item-'+i+'-quantity, #item-'+i+'-unit-price').on('input',function(e){
$('#Total').val(parseFloat($('#item-'+i+'-quantity').val()) * parseFloat($('#item-'+i+'-unit-price').val()));
});
}
When i input values(quantity and unit-price), i don't get the total.The For Loop doesn't work. Please help,thanks.
Try this:
//loop by name
$("input[name=quantity], input[name=unit_price]").on('input', function () {
var total = 0;
$("input[name=quantity]").each(function (i, e) {
total += $(this).val() * $(e).closest("tr").find("input[name=unit_price]").val();
});
$('#Total').val(total);
});
//loop by table
$("#myTable input[type=number]").on('input', function () {
var total = 0;
$("#myTable tr").each(function (i, e) {
if (document.getElementById("item-" + i + "-quantity") && document.getElementById("item-" + i + "-unit_price")) {//just check if elements exists
total += $(e).find("#item-" + i + "-quantity").val() * $(e).find("#item-" + i + "-unit_price").val();
}
});
$('#Total_by_table_rows').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="form">
<tbody>
<tr class="">
<td>
<input type="number" name="quantity" id="item-0-quantity">
</td>
<td>
<input type="number" name="unit_price"id="item-0-unit_price">
</td>
</tr>
<tr>
<td>
<input type="number" name="quantity" id="item-1-quantity">
</td>
<td>
<input type="number" name="unit_price"id="item-1-unit_price">
</td>
</tr>
</tbody>
</table>
<label> Total:
<input id="Total">
</label>
<label> Total by table rows:
<input id="Total_by_table_rows">
</label>
Because the content you want to sum is identified with the "quantity" and "unit_price" name attributes, you can use this:
$('tr').each(function() {
sum += $('input[name="quantity"]', this).val() * $('input[name="unit_price"]', this).val();
})
The second parameter in the selector (this in our case) give jQuery a context for the search, i.e., each of the rows of the table.
Here you have the snippet:
$('#calculate').click(function() {
var sum = 0;
$('tr').each(function() {
sum += $('input[name="quantity"]', this).val() * $('input[name="unit_price"]', this).val();
})
$('#result').text(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="form">
<tbody>
<tr>
<td>
<input type="number" name="quantity" value="0">
</td>
<td>
<input type="number" name="unit_price" value="0">
</td>
</tr>
<tr>
<td>
<input type="number" name="quantity" value="0">
</td>
<td>
<input type="number" name="unit_price" value="0">
</td>
</tr>
</tbody>
</table>
<input type="button" value="Calculate" id="calculate">
<div>
Result: <span id="result"></span>
</div>
Here you can do like this.
Your code is not working becuase of
var rowCounter = $("#myTable tr").length - 1;
for (var i = 0; i <= rowCounter; i++) {
$('#item-'+i+'-quantity, #item-'+i+'-unit-price').on('input',function(e){
$('#Total').val(parseFloat($('#item-'+i+'-quantity').val()) * parseFloat($('#item-'+i+'-unit-price').val()));
});
}
For Loop was executes before your type in input fields.
And also you have some mistake in code too like here you wrote $('#item-'+i+'-unit-price') but it should be like this $('#item-'+i+'-unit_price')
var quantity = $("input[name='quantity']");
$("input[name='quantity'], input[name='unit_price']").on('input',function(){
var total = 0;
$(quantity).each(function(){
total += parseFloat($(this).val()) * parseFloat($(this).parent().next().find("input[name='unit_price']").val());
});
$("#Total span").html(total);
});
td {
width: 80%;
float: left;
margin-left: 10px;
}
label {
width: 20%;
float: left
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="form">
<tbody>
<tr class="">
<td>
<label>Quantity 1</label>
<input type="number" name="quantity" id="item-0-quantity" />
</td>
<td>
<label>Unit Price 1</label>
<input type="number" name="unit_price"id="item-0-unit_price" />
</td>
<td>
<label>Quantity 1</label>
<input type="number" name="quantity" id="item-1-quantity" />
</td>
<td>
<label>Unit Price 1</label>
<input type="number" name="unit_price"id="item-1-unit_price" />
</td>
<td id="Total">
<label>Total</label>
<span></span>
</td>
</tr>
</tbody>
</table>

Have same DIV display for different HTML Tabs

I have a set of 10 Search Fields to be displayed when 2 different tabs are clicked. Both the tabs have same set of 10 fields. Instead of having different DIV, I want to use same DIV and based on the specific TAB selection, I want to only change my AJAX REST End-Point.
Pls help how to use same DIV for different TABS in HTML.
1) HTML: Code below shows 2 tabs and the 2 DIVs - Entity and Claim. Want to use only 1 DIV as both ENTITY and CLAIM DIVs have same set of fields.
<div class="tab">
<button class="tablinks" name="entity"
onclick="openTab(event, 'entity')" id="defaultOpen">Entity
Search</button>
<button class="tablinks" name="claim" onclick="openTab(event, 'claim')">Claim
Search</button>
</div>
<div id="entity1" class="tabcontent">
<h3>Entity</h3>
</div>
<div id="claim1" class="tabcontent">
<h3>Claim</h3>
</div>
<div id="entity" style="text-align: center" class="tabcontent">
<form name="ajaxform" id="ajaxform" method="POST" align="center">
<label align="center" class="h1"><font size=6><b>ER
Search Service</b></font></label> </br> </br> </br>
<input type="hidden" id="userID" name="userID" value="">
<script>
</script>
<table align="center">
<tr>
<td>EntityID</td>
<td><input type="text" name="entityid" width=10></td>
<!-- <td>ClaimID</td>
<td><input type="text" name="claimid" width=10></td> -->
<td>First Name</td>
<td><input type="text" name="firstname" width=10></td>
<td>Last Name</td>
<td><input type="text" name="lastname" width=10></td>
</tr>
<tr>
<td>Address Line 1</td>
<td><input type="text" name="addrLine1" width=10></td>
<td>Address Line 2</td>
<td><input type="text" name="addrLine2" width=10></td>
<td>City</td>
<td><input type="text" name="city" width=10></td>
<td>State</td>
<td><input type="text" name="state" width=10></td>
</tr>
<tr>
<td>Country</td>
<td><input type="text" name="country" width=10></td>
<td>Zipcode</td>
<td><input type="text" name="zipcode" width=10></td>
<td>SSN</td>
<td><input type="text" name="ssn" width=10></td>
<td>DL Number</td>
<td><input type="text" name="dl_num" width=10></td>
</tr>
<tr>
<td>DOB</td>
<td><input type="text" name="dob" width=10></td>
<td>Professional License</td>
<td><input type="text" name="profLic" width=10></td>
<td>Policy Number</td>
<td><input type="text" name="policyNum" width=10></td>
</tr>
</table>
</br>
<table align="center" class="h1">
<tr>
<td><input type="button" id="simplepost" value="Search"
align="center"></td>
<td><input type="reset" id="reset" value="Clear"
onClick="runReset()" align="center"></td>
</tr>
</table>
</br>
<table align="center" class="h1">
<tr>
<td><select id="downloadFormat" align="center">
<option value="selectValue" selected>Select Download
Format</option>
<option value="csv">CSV</option>
<option value="xls">Excel</option>
<option value="xml">XML</option>
<option value="pdf">PDF</option>
</select></td>
<td><input type="button" id="download" value="Download"
disabled=true align="center"></td>
</tr>
</table>
</form>
</div>
<div id="claim" style="text-align: center" class="tabcontent">
<form name="claimform" id="claimform" method="POST" align="center">
<label align="center" class="h1"><font size=6><b>ER
Search Service</b></font></label> </br> </br> </br>
<table align="center">
<tr>
<td>EntityID</td>
<td><input type="text" name="entityid" width=10></td>
<td>ClaimID</td>
<td><input type="text" name="claimid" width=10></td>
<td>First Name</td>
<td><input type="text" name="firstname" width=10></td>
<td>Last Name</td>
<td><input type="text" name="lastname" width=10></td>
</tr>
<tr>
<td>Address Line 1</td>
<td><input type="text" name="addrLine1" width=10></td>
<td>Address Line 2</td>
<td><input type="text" name="addrLine2" width=10></td>
<td>City</td>
<td><input type="text" name="city" width=10></td>
<td>State</td>
<td><input type="text" name="state" width=10></td>
</tr>
<tr>
<td>Country</td>
<td><input type="text" name="country" width=10></td>
<td>Zipcode</td>
<td><input type="text" name="zipcode" width=10></td>
<td>SSN</td>
<td><input type="text" name="ssn" width=10></td>
<td>DL Number</td>
<td><input type="text" name="dl_num" width=10></td>
</tr>
<tr>
<td>DOB</td>
<td><input type="text" name="dob" width=10></td>
<td>Professional License</td>
<td><input type="text" name="profLic" width=10></td>
<td>Policy Number</td>
<td><input type="text" name="policyNum" width=10></td>
</tr>
</table>
</br>
<table align="center" class="h1">
<tr>
<td><input type="button" id="claimpost" value="Search"
align="center"></td>
<td><input type="reset" id="reset" value="Clear"
onClick="runReset()" align="center"></td>
</tr>
</table>
</br>
<table align="center" class="h1">
<tr>
<td><select id="downloadFormat" align="center">
<option value="selectValue" selected>Select Download
Format</option>
<option value="csv">CSV</option>
<option value="xls">Excel</option>
<option value="xml">XML</option>
<option value="pdf">PDF</option>
</select></td>
<td><input type="button" id="download" value="Download"
disabled=true align="center"></td>
</tr>
</table>
</form>
</div>
2) JavaScript:
<script>
var tabSelected = '';
var userID = getParameterByName("userID");
//alert(userID);
function setUserID() {
//userID = getParameterByName("userID");
document.getElementById("userID").value = userID;
//alert(document.getElementById("userID").value);
}
function getParameterByName(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
//alert('Query Variable ' + variable + ' not found');
}
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
if (tabName == "entity") {
tabSelected = "getEntity";
alert(tabSelected);
} else if (tabName == "claim") {
tabSelected = "getClaim";
alert(tabSelected);
}
}
document.getElementById("defaultOpen").click();
</script>
3) AJAX:
$("#simplepost").click(function(e) {
//getUsersAndDisplay();
tabSelected = "getEntity";
//alert(tabSelected);
convertJSONToTable(tabSelected);
});
//GETUSERS Button ends
$("#claimpost").click(function(e) {
tabSelected = "getClaim";
//alert(tabSelected);
convertJSONToTable(tabSelected);
});
AJAX REST-ENDPOINT CALL: Want to call same method based on the variable which is getting the right values. But problem is how to display same DIV for different TAB Selections.
function convertJSONToTable(tab) {
var MyFormData = $("#ajaxform").serializeJSON();
console.log(MyFormData);
var MyFormJSON = JSON.stringify(MyFormData,null, 2);
console.log(MyFormJSON);
var urlSelected = '';
if (tab == "getEntity") {
urlSelected = "http://localhost:8089/restserver/rest/getEntity";
} else if (tab == "getClaim"){
urlSelected = "http://localhost:8089/restserver/rest/getClaim";
}
$.ajax({
url : urlSelected,
type: "POST",
contentType: "application/json",
data : MyFormJSON,
success: function(response) {
//Store result in Session and Enable Download button
response = removeAllBlankOrNull(response);
var cacheString = JSON.stringify(response, null, 2);
console.log("-----------------> cacheString is: " + cacheString);
var sessionresponse = sessionStorage.setItem("i98779", cacheString);
console.log("----------------------------------------------------------------");
console.log("Response is: " + response);
console.log("----------------------------------------------------------------");
if(cacheString != null && cacheString != "[]") {
document.getElementById("download").disabled = false;
}
createTable2(response);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(errorThrown);
alert("Error: " + errorThrown);
}
});
} //convertJSONToTable() Ends here
You only need one form and therefore only one "tab". But with two buttons you can let it appear like having two tabs. Each of these buttons shows/hide a submit-button in the form.
The form has to submit-buttons. One is sending the variable "claim" to the ajax-function. The other one is sending "entity" to the ajax-function.
HTML
<div class="tab">
<button class="tablinks" name="entity" id="open-entity">Entity
Search</button>
<button class="tablinks" name="claim" id="open-claim">Claim
Search</button>
</div>
<div>
<form>
<!--Input fields goes here-->
<!--Two submit buttons in the same form, each is sending its individual variable to your ajax function-->
<input type="button" id="submit-entity" value="Download"
disabled=true align="center">
<input type="button" id="submit-claim" value="Download"
disabled=true align="center"></td>
</form>
</div>
JS
$(function() {
//Define which form should be shown on page-load, in this case "claim"
$('#submit-claim').show();
$('#submit-claim').hide();
//Show button to submit claim-form, hide button for entity-form
$('#open-claim').click(function(){
$('#submit-claim').show();
$('#submit-claim').hide();
});
//Hide button to submit claim-form, show button for entity-form
$('#open-entity').click(function(){
$('#submit-entity').show();
$('#submit-entity').hide();
});
//Call ajax if submit button is clicked
$('#submit-entity').click(function(){
convertJSONToTable('entity');
});
$('#submit-claim').click(function(){
convertJSONToTable('claim');
});
});
SECOND OPTION:
Instead of having two submit buttons you can add a hidden input-field to your form. If the user clicks on the #open-claim button the value of the input field is changed to 'claim'. If clicked on open-entityits value gets 'entity'.
$('#open-claim').click(function(){
$('#form-type').val('claim');
});
$('#open-entity').click(function(){
$('#form-type').val('entity');
});
Then, when clicked on the submit-button of the form the value of the input field is sent to the ajax-function.
$('#submit-btn').click(function(){
convertJSONToTable($('#form-type').val());
});

Autofill other fields automatically if one field is entered with jquery

Please check my fiddle.
Fiddle
When i enter any data in any rows in slab_range, i need to autofill all the other rows of 'Slab Range' with a value 'No Bid'. If i left blank, nothing has to be filled. Likewise if i enter any data in 'Part Number', all the other rows of 'Part Number' has to be filled with value '2'. The rows are coming from db, so i cant tell how many rows it will be, it should iterate all the rows.
<tr>
<td>
<input size="1" id="sl[0]" name="sl[0]" value="1" type="text">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
There you go, now it's your task to refactoring the code because both methods are equals.
var ProcessTable = (function () {
var _slabs, _partsNumber;
var _init = function () {
_slabs = $('input[name^="slab_range"]');
_partsNumber = $('input[name^="item_partno"]');
_slabs.on('blur', _slabBlurHandler);
_partsNumber.on('blur', _partNumberBlurHandler);
};
var _slabBlurHandler = function (e) {
var value = $.trim($(this).val());
if (value !== '') {
_slabs.val('No bid');
} else {
_slabs.val('');
}
$(this).val(value); // Because the previous line override the original value
};
var _partNumberBlurHandler = function (e) {
var value = $.trim($(this).val());
if (value !== '') {
_partsNumber.val('2');
} else {
_partsNumber.val('');
}
$(this).val(value); // Because the previous line override the original value
};
return {
init: _init
}
})();
ProcessTable.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="cart1" name="cart" method="post" class="single" action="price_edit_save.php?supplier_name=Jupiter+Microwave+Components+Inc&tender_id=151501">
<div class="clone_row">
<table style="border-collapse: collapse;" id="table" border="1" cellpadding="2" cellspacing="2" width="100%">
<thead>
<tr bgcolor="#E6E6FA">
<th width="4%">SlNo</th>
<th width="4%">Slab Range</th>
<th width="6%">Part Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input size="1" name="id[0]" value="9978" readonly="readonly" type="hidden">
<input size="1" id="sl[0]" name="sl[0]" value="1" type="text">
<input size="1" id="item_id[0]" name="item_id[0]" readonly="readonly" type="hidden">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
<tr>
<td>
<input size="1" name="id[1]" value="9979" readonly="readonly" type="hidden">
<input size="1" id="sl[1]" name="sl[1]" value="2" type="text">
<input size="1" id="item_id[1]" name="item_id[1]" readonly="readonly" type="hidden">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
<tr>
<td>
<input size="1" name="id[1]" value="9979" readonly="readonly" type="hidden">
<input size="1" id="sl[1]" name="sl[1]" value="2" type="text">
<input size="1" id="item_id[1]" name="item_id[1]" readonly="readonly" type="hidden">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
</tbody>
</table>
</div>
<div class="addMoreDIV">
</div>
<table>
<tr>
<td>
<input value="--Update Data--" type="submit">
</td>
</tr>
</table>
</form>
And please, be more kindly when you ask for "help".

input array values sum using javascript

I have input fields like this
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
.
.
.
<input name="total" type="text" id="total" value="">
if i enter value in unittotal field onchange the final text box value is should be sum of that unit total using javascript.
Here's the working demo for you.
You need not use duplicate id values for your HTML elements. Consider using class name instead. Refer the markup and the code that calculates the total. I hope its self-explanatory enough.
JavaScript:
function updateTotal() {
var total = 0;//
var list = document.getElementsByClassName("input");
var values = [];
for(var i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
total = values.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
document.getElementById("total").value = total;
}
HTML:
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input name="total" type="text" id="total" value="">
Like this:
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<hr>
<input type="text" size="3" id="sum" />
and the javascript:
(function () {
var elms = document.querySelectorAll('.add'),
arr = Array.prototype.slice.call(elms),
onChange = function () {
var result = 0;
arr.forEach(function (el) {
result = result + +el.value;
});
document.getElementById('sum').value = result;
};
arr.forEach(function (el) {
el.addEventListener('change', onChange);
});
}());
http://jsfiddle.net/65b6T/
try this , and see in detail in fiddle DEMO.
HTML
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
<tr>
<td width="40px">1</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr id="summation">
<td align="left">Total :</td>
<td align="left"><span id="sum">0</span>
</td>
</tr>
</table>
Javascript:
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function () {
$(this).keyup(function () {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
Here is a DEMO for this solution. http://jsfiddle.net/jxJg7/1/
NOTES:
It works only if your values are integers.
I created a function that will force the user to put numbers only on the inputs
Make sure you remove the duplicated IDs
<script type="text/javascript">
function sumofunittotal() {
var total = 0;
var cusid_ele = document.getElementsByClassName('inputtosum');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseInt(cusid_ele[i].value)) )
total += parseInt(cusid_ele[i].value);
}
document.getElementById('total').value=total;
}
function onlynumber(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
</script>
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="total" type="text" id="total" value="">

Categories