Javascript Forms Calculator with No answers - javascript

I am very new to really writing javascript (borrowing and editing, not so new). So with a little help from google and code guru and adobe cookbook, I have come up with this simple form to be embedded into an iPad publication (this is just my test, not the final product). I have gotten it this far with no errors if the debug console and it seems to pass W3C compliance, but it also doesn't do anything! It doesn't generate the answers??? I am hoping someone can help me out or steer me in the right direction. the code for the page is below: Thanks in advance...
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.innerHTML = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.innerHTML = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.innerHTML = + (TotalsCost1 - TotalsCost2);
}
};
</script>
</body>

btn.onclick = (function(){...})();
You need to put onclick events inside self-calling code, or what are called closures. Move your entire btn.onclick function inside of this bit of code: (...)() in order to make it work.

Good attempt, a few small things wrong but pretty close!
I have made a few changes here.
As mentioned in a comment, I wrapped the function with brackets (function() {...});
I also changed innerHTML to be value as we are updating text inputs, and your savings calculation should be input.value, which I have updated for you.
Let me know how you get on!
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = (function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.value = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.value = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.value = + (TotalsCost1.value - TotalsCost2.value);
}
});
</script>
</body>

Related

JavaScript text box addition

I am working on a form to create an invoice.
so basically, i have a button to create a table row where I can enter the code, name of product, notes, qty, price and discount. then automatically add the total price, by multiply the qty and subtracting the discount.
The problem I am having is to get the row index where the addition need to be worked. The first row it works but the second, third, etc... doesn't work.
I am asking here maybe there is some one that can find the problem. I am a beginner when it comes to javascript and basically learning while working on it, so any help it is really appreciated.
// Item Counter
var ic = 1;
// Remove an entry
function RemoveEntryFromList(entry) {
document.getElementById(entry).remove();
}
// Adds an entry into the "Added Items" list
function addEntryToList(p_code, p_name, p_sn, p_qty, p_price, p_discount, p_url, p_costPrice, p_qtyAvailable) {
var entry = document.createElement("tr");
entry.id = ("item-" + String(ic));
document.getElementById("list-table").tBodies[0].appendChild(entry);
p_price1 = parseFloat(p_price).toFixed(2);
p_costPrice1 = parseFloat(p_costPrice).toFixed(2);
entry.innerHTML = `<td><input value="${p_code}" /></td>
<td><input value="${p_name}" /></td>
<td><input value="${p_sn}" /></td>
<td><input type="text" id="qty" value="${p_qty}" oninput="calculate()" /></td>
<td><input type="text" id="price" step="0.01" min="0.00" value="${p_price1}" oninput="calculate()" /></td>
<td><input type="text" id="discount" value="${p_discount}" oninput="calculate()" /></td>
<td><input type="number" id="net_price" readonly /></td>
<td style="text-align: center;"><button onclick="RemoveEntryFromList('${entry.id}')"> X </button></td>
<td style="text-align: center; cursor: pointer;"><i class="fas fa-ellipsis-v"></i></td>`;
ic++;
}
function calculate() {
var calc_qty = document.getElementById('qty').value;
var calc_price = document.getElementById('price').value;
var discount = document.getElementById('discount').value;
var result = document.getElementById('net_price');
var calc_discount = calc_price * (discount / 100);
var calc_result = (calc_price - calc_discount) * calc_qty;
result.value = calc_result;
}
<div id="container">
<div id="list-sect">
<button id="add-custom-item-btn" onClick="addEntryToList('', '', '', '1', '0.00', '0');" style="height: 30px;">
<i class="fas fa-box-open"></i> Add New Entry
</button>
</div>
<table id="list-table">
<tr class="list-entry" style="height: 21px;">
<th width="80px">Code</th>
<th>Name</th>
<th>notes</th>
<th width="60px">Qty</th>
<th width="76px">Price</th>
<th width="65px">Disc.(%)</th>
<th width="76px">Total Price</th>
<th colspan="2">Remove</th>
</tr>
</table>
</div>
Don't use id's in your generated code, id's have to be unique. I changed them to classes. I also changed the calculate function so the target element is given as a parameter. In the calculate function the correct elements are found based on the element in the parameter.
But it's a pretty ugly way of handling this. I recommend rewrite it so you do event delegation on your table like in the function below. If you don't want that then see the bottom snippet.
//Event delgation from the table as replacement of the calculate function
document.querySelector('#list-table').addEventListener('input', function(e) {
//Element that triggered
let target = e.target;
//check if the target has the class of one of our input elements that we want to use for (re)calculation
if (target.classList.contains('qty') ||
target.classList.contains('price') ||
target.classList.contains('discount') ||
target.classList.contains('net_price')
) {
//(re)calculate
var targetRow = target.parentElement.parentElement;
var calc_qty = targetRow.querySelector('.qty').value;
var calc_price = targetRow.querySelector('.price').value;
var discount = targetRow.querySelector('.discount').value;
var result = targetRow.querySelector('.net_price');
var calc_discount = calc_price * (discount / 100);
var calc_result = (calc_price - calc_discount) * calc_qty;
result.value = calc_result;
}
});
// Item Counter
var ic = 1;
// Remove an entry
function RemoveEntryFromList(entry) {
document.getElementById(entry).remove();
}
// Adds an entry into the "Added Items" list
function addEntryToList(p_code, p_name, p_sn, p_qty, p_price, p_discount, p_url, p_costPrice, p_qtyAvailable) {
var entry = document.createElement("tr");
entry.id = ("item-" + String(ic));
document.getElementById("list-table").tBodies[0].appendChild(entry);
p_price1 = parseFloat(p_price).toFixed(2);
p_costPrice1 = parseFloat(p_costPrice).toFixed(2);
entry.innerHTML = `<td><input value="${p_code}" /></td>
<td><input value="${p_name}" /></td>
<td><input value="${p_sn}" /></td>
<td><input type="text" class="qty" value="${p_qty}" /></td>
<td><input type="text" class="price" step="0.01" min="0.00" value="${p_price1}" /></td>
<td><input type="text" class="discount" value="${p_discount}" /></td>
<td><input type="number" class="net_price" readonly /></td>
<td style="text-align: center;"><button onclick="RemoveEntryFromList('${entry.id}')"> X </button></td>
<td style="text-align: center; cursor: pointer;"><i class="fas fa-ellipsis-v"></i></td>`;
ic++;
}
<div id="container">
<div id="list-sect">
<button id="add-custom-item-btn" onClick="addEntryToList('', '', '', '1', '0.00', '0');" style="height: 30px;">
<i class="fas fa-box-open"></i> Add New Entry
</button>
</div>
<table id="list-table">
<tr class="list-entry" style="height: 21px;">
<th width="80px">Code</th>
<th>Name</th>
<th>notes</th>
<th width="60px">Qty</th>
<th width="76px">Price</th>
<th width="65px">Disc.(%)</th>
<th width="76px">Total Price</th>
<th colspan="2">Remove</th>
</tr>
</table>
</div>
Original answer:
// Item Counter
var ic = 1;
// Remove an entry
function RemoveEntryFromList(entry) {
document.getElementById(entry).remove();
}
// Adds an entry into the "Added Items" list
function addEntryToList(p_code, p_name, p_sn, p_qty, p_price, p_discount, p_url, p_costPrice, p_qtyAvailable) {
var entry = document.createElement("tr");
entry.id = ("item-" + String(ic));
document.getElementById("list-table").tBodies[0].appendChild(entry);
p_price1 = parseFloat(p_price).toFixed(2);
p_costPrice1 = parseFloat(p_costPrice).toFixed(2);
entry.innerHTML = `<td><input value="${p_code}" /></td>
<td><input value="${p_name}" /></td>
<td><input value="${p_sn}" /></td>
<td><input type="text" class="qty" value="${p_qty}" oninput="calculate(this)" /></td>
<td><input type="text" class="price" step="0.01" min="0.00" value="${p_price1}" oninput="calculate(this)" /></td>
<td><input type="text" class="discount" value="${p_discount}" oninput="calculate(this)" /></td>
<td><input type="number" class="net_price" readonly /></td>
<td style="text-align: center;"><button onclick="RemoveEntryFromList('${entry.id}')"> X </button></td>
<td style="text-align: center; cursor: pointer;"><i class="fas fa-ellipsis-v"></i></td>`;
ic++;
}
function calculate(element) {
var calc_qty = element.parentElement.parentElement.querySelector('.qty').value;
var calc_price = element.parentElement.parentElement.querySelector('.price').value;
var discount = element.parentElement.parentElement.querySelector('.discount').value;
var result = element.parentElement.parentElement.querySelector('.net_price');
var calc_discount = calc_price * (discount / 100);
var calc_result = (calc_price - calc_discount) * calc_qty;
result.value = calc_result;
}
<div id="container">
<div id="list-sect">
<button id="add-custom-item-btn" onClick="addEntryToList('', '', '', '1', '0.00', '0');" style="height: 30px;">
<i class="fas fa-box-open"></i> Add New Entry
</button>
</div>
<table id="list-table">
<tr class="list-entry" style="height: 21px;">
<th width="80px">Code</th>
<th>Name</th>
<th>notes</th>
<th width="60px">Qty</th>
<th width="76px">Price</th>
<th width="65px">Disc.(%)</th>
<th width="76px">Total Price</th>
<th colspan="2">Remove</th>
</tr>
</table>
</div>
in order for your code to work using document.getElementById("list-table").tBodies[0].appendChild(entry); you need to enclose your rows (<tr>) inside a <tbody> </tbody>.
also i'd change your entry.innerHTML = (...) to add each td as a new createElement() inside entry.

Can I append/push values of html elements to each row of an array generated from a html table within the form?

I'm doing a html form for online requests by users. The form has text input fields for user contact details (e.g. user name, department, email, etc) at the top, followed by a table with multiple rows for different items requested.
I want to have the form data appended into Google Sheets, where each table row (item requested) is appended as a separate row in Sheets, with the user contact details added to each row, i.e. the contact details have to repeat for the same user.
Link to Sheet
Tried Google Forms -- it's good for single item requests -- one Google Form for one item. But for multiple item requests by the same user, the user has to key in contact details repeatedly. Branching to repeat sections in Forms didn't work, since additional items are added as new columns and not as a new row. Thus I tried a rudimentary html form.
FormTableDialog
Code.gs:
function addRows(valuesAll) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
sheet.getRange(sheet.getLastRow()+1,1,valuesAll.length,valuesAll[0].length).setValues(valuesAll);
}
Html:
<!DOCTYPE html>
<html>
<head>
<?!= include('CSS_Table'); ?>
</head>
<body>
Name: <input type="text" id="Name"><br>
Phone: <input type="text" id="Phone"><br>
Email: <input type="email" id="Email"><br>
Department: <input type="text" id="Dept"><br>
<table id="tableRows">
<thead>
<tr>
<th>Item</th>
<th>Description</th>
<th>Quantity</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
</tr>
<tr>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
</tr>
<tr>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
</tr>
<tr>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
</tr>
<tr>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
<td><input class="inputCell" type="text"></td>
</tr>
<tbody>
</table>
<div class="buttonBar">
<input class="inputButton" type="button" value="Submit" onclick="buttonClick(this)">
<input class="inputButton" type="button" value="Cancel" onclick="buttonClick(this)">
</div>
<?!= include('JS_Table'); ?>
</body>
JS_Table.html:
<script>
function buttonClick(button) {
if( button.value === "Submit" ) {
var values = [];
var table = document.getElementById("tableRows");
for( var i=1; i<table.rows.length; i++ ) {
values.push([]);
var row = table.rows[i];
for( var j=0; j<row.cells.length; j++ ) {
var cell = row.cells[j].firstChild.value;
values[i-1].push(cell)
var user = ["Name","Phone","Email","Dept"];
var valuesAll = values.concat(user)
}
}
google.script.run.addRows(valuesAll);
google.script.host.close();
}
else {
if( confirm("Exit without saving?") ) google.script.host.close();
}
}
</script>
Tried to simply concat the id's of the user details, with the table array. But the google script didn't work. Appreciate any suggestions for this newbie.
The Execution Transcript:
[19-05-25 19:42:15:580 PDT] Starting execution
[19-05-25 19:42:15:587 PDT] SpreadsheetApp.getActiveSpreadsheet() [0 seconds
[19-05-25 19:42:15:672 PDT] Spreadsheet.getSheetByName([Sheet1]) [0.084 seconds]
[19-05-25 19:42:15:772 PDT] Sheet.getLastRow() [0.099 seconds]
[19-05-25 19:42:15:772 PDT] Sheet.getRange([2, 1, 9, 4]) [0 seconds]
[19-05-25 19:42:15:779 PDT] Execution failed: Cannot convert Array to Object[][]. (line 17, file "Code") [0.189 seconds total runtime]
There are two problems with the OPs code.
1 - output is not adjusted for Google's two-dimensional range.
2 - the Name, phone, email and department are not collected.
The following answer is written to work in the sidebar (not essential) and also tests whether the form data is complete - that is: whether there is complete data for the Item, Description, Quantity and Location in each row . The OP can easily remove this test.
56302393_04_gs.gs
function showSidebar04() {
var htmlOutput = HtmlService.createHtmlOutputFromFile("56302393_04_html");
htmlOutput.setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle("56302393_04 Form");
var ui = SpreadsheetApp.getUi();
ui.showSidebar(htmlOutput);
}
function addRows04(valuesAll) {
//Logger.log("DEBUG: valuesall = "+valuesAll);
var testdata = [];
var testdata = valuesAll.slice(0);
// Logger.log("DEBUG: testdata = "+testdata);
// remove the name fields
testdata.splice(0, 4);
// get the number of fields
var testdatalength = (testdata.length);
// Logger.log("DEBUG: testdata length = "+testdatalength);
// get the number of empty fields - were looking for rows that are inclonplete
var newempties = testdatalength - testdata.filter(String).length;
var adjustedlength = testdatalength-newempties;
//Logger.log("DEBUG: newempties = "+newempties+", so adjusted length = "+adjustedlength);
// calculate the number of rows
var netrows = adjustedlength/4;
// Logger.log("DEBUG: adjusted length divided by 4 = "+netrows);
// is the result an integers - get the mod
var netrowMod = adjustedlength % 4;
// Logger.log("DEBUG: residual = "+netrowMod);
// test whether newrows is an integer by testing whether mode = 0
if(netrowMod !== 0){
// Logger.log("DEBUG: netrows: "+netrows+" is not an integer");
Browser.msgBox("The data rows were not completed evenly. Code aborted");
return;
}
// setup the spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = "Sheet1";
var sheet = ss.getSheetByName("Sheet1");
var lastrow = sheet.getLastRow();
// get the name data
var name = valuesAll[0];
var phone = valuesAll[1];
var email = valuesAll[2];
var dept = valuesAll[3];
// set the range
var outputRange = sheet.getRange(lastrow+1,1,netrows,8);
// Logger.log("DEBUG Output range = "+range.getA1Notation());
var datastart = 4;
var alldata = [];
for (var i = 0; i<netrows;i++){
var datarow = [];
// get the row information
var item = valuesAll[(i*datastart)+4];
var desc = valuesAll[(i*datastart)+5]
var qty = valuesAll[(i*datastart)+6];
var locn = valuesAll[(i*datastart)+7];
// Logger.log("DEBUG: i="+i+", values = "+item+" "+desc+" "+qty+" "+locn);
// build the row fields
datarow.push(item);
datarow.push(desc);
datarow.push(qty);
datarow.push(locn);
datarow.push(name);
datarow.push(phone);
datarow.push(email);
datarow.push(dept);
// accumulate the rows
alldata.push(datarow);
//Logger.log("DEBUG: datarow = "+datarow)
//Logger.log("DEBUG: alldata = "+alldata)
}
// update the values of the outputrange
outputRange.setValues(alldata);
}
56302393_04_html.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="tableName">
<tbody>
<tr><td>Name:</td><td> <input type="text" name="name" value="Fred"></td></tr>
<tr><td>Phone: </td><td><input type="text" name="phone" value="0412987654"></td></tr>
<tr><td>Email: </td><td><input type="email" name="email" value="fred#example.com"></td></tr>
<tr><td>Department: </td><td><input type="text" name="dept" value="Sydney"></td></tr>
</tbody>
</table>
<style>
.inputCell { float: right; width: 40%; }
.inputCell { float: left; width: 80%; }
.inputButton { float: left; width: 50%; }
</style>
<table id="tableRows">
<thead>
<tr>
<th>Item</th>
<th>Description</th>
<th>Quantity</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="inputCell" type="text" value="1"></td>
<td><input class="inputCell" type="text" value="amd"></td>
<td><input class="inputCell" type="text" value="11"></td>
<td><input class="inputCell" type="text" value="B12"></td>
</tr>
<tr>
<td><input class="inputCell" type="text" value="2"></td>
<td><input class="inputCell" type="text" value="ibm"></td>
<td><input class="inputCell" type="text" value="22"></td>
<td><input class="inputCell" type="text" value="Z23"></td>
</tr>
<tr>
<td><input class="inputCell" type="text" value="3"></td>
<td><input class="inputCell" type="text" value="digital"></td>
<td><input class="inputCell" type="text" value="33"></td>
<td><input class="inputCell" type="text" value="A49"></td>
</tr>
<tr>
<td><input class="inputCell" type="text" value="4"></td>
<td><input class="inputCell" type="text" value="apple"></td>
<td><input class="inputCell" type="text" value="44"></td>
<td><input class="inputCell" type="text" value="K12"></td>
</tr>
<tr>
<td><input class="inputCell" type="text" value="5"></td>
<td><input class="inputCell" type="text" value="rex"></td>
<td><input class="inputCell" type="text" value="55"></td>
<td><input class="inputCell" type="text" value="ascot"></td>
</tr>
<tbody>
</table>
<div class="buttonBar">
<input class="inputButton" type="button" value="Submit" onclick="buttonClick(this)">
<input class="inputButton" type="button" value="Cancel" onclick="buttonClick(this)">
</div>
<script>
function buttonClick(button) {
if( button.value === "Submit" ) {
var valuesAll = [];
// Collect name details
var tablename = document.getElementById("tableName");
var myname = tablename.rows[0].cells[1].children[0].value
var myphone = tablename.rows[1].cells[1].children[0].value
var myemail = tablename.rows[2].cells[1].children[0].value
var mydept = tablename.rows[3].cells[1].children[0].value
valuesAll.push(myname);
valuesAll.push(myphone);
valuesAll.push(myemail);
valuesAll.push(mydept);
// collect row details
var table = document.getElementById("tableRows");
for( var i=1; i<table.rows.length; i++ ) {
var row = table.rows[i];
for( var j=0; j<row.cells.length; j++ ) {
var cell = row.cells[j].firstChild.value;
valuesAll.push(cell);
}
}
google.script.run.addRows04(valuesAll);
google.script.host.close();
}
else {
if( confirm("Exit without saving?") ) google.script.host.close();
}
}
</script>
</body>
Output screenshot

How to calculate to variable in javascript and print them in the html page

I try to get result from html table witch excepted only numbers i check them throw if statement if variable 1 bigger than variable 2 print content and that works good.
Now i am trying in the if statement to print variable 1 - variable 2 but it doesn't wanna work.
Here is the snippet:
$(document).ready(function() {
var vastInkomen = 0;
$('.txtBox').keyup(function() {
vastInkomen = 0;
$('.txtBox').each(function() {
var txtBoxVal = $(this).val();
vastInkomen += Number(txtBoxVal);
});
$('#vastInkomen').val(vastInkomen);
writeResult();
});
var vastLasten = 0;
$('.vast_lasten').keyup(function() {
vastLasten = 0;
$('.vast_lasten').each(function() {
var vastLastenVal = $(this).val();
vastLasten += Number(vastLastenVal);
});
$('#vastLasten').val(vastLasten);
writeResult();
});
function writeResult() {
if (vastInkomen !== 0 && vastLasten !== 0) {
if (vastInkomen > vastLasten) {
$('#result').text("Some text and work good!") +
vastLasten - vastInkomen;
} else if (vastInkomen < vastLasten) {
//$('#result-amount').console(vastInkomen -vastLasten);
$('#result').text("some text and work good.");
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>content1</td>
<td><input class="txtBox" type="number" name="content2" />
</td>
</tr>
<tr>
<td>content3</td>
<td><input class="txtBox" type="number" name="content3" />
</td>
</tr>
<tr>
<td>content4</td>
<td>
<input class="txtBox" type="number" name="content4" />
</td>
</tr>
</table>
<table>
<tr>
<td>content</td>
<td><input class="vast_lasten" type="number" name="content" /></td>
</tr>
<tr>
<td>content1</td>
<td><input class="vast_lasten" type="number" name="content1" /></td>
</tr>
<tr>
<td>content2</td>
<td><input class="vast_lasten" type="texnumber" name="content2" /></td>
</tr>
</table>
<div class="col">
<h3>Het resultaat is:</h3>
<p id="result"></p>
</div>
This will work:
var result = vastLasten - vastInkomen;
$('#result').text("Some text and work good!" + result);
You can use .text() to set the content of an element, but everything should be within the parenthesis.
I added an extra variable result because you cannot use + and - both here; it will result in NaN as it will try to sum the values.
This works as well:
$('#result').text("Some text and work good!" + (vastLasten - vastInkomen));

Value passed from textbox to textarea is automatically deleted

I am trying to pass a value entered in a textbox to a text area. However when I run my code the value appears in the textarea and it disapears.
Html code:
Customer Name
<input type="text" id="name1TXT" />
<textarea rows="6" cols="50" id="productList">
</textarea>
Javascript:
function transferData() {
var customer = document.getElementById("name1TXT").value;
if (customer != "")
document.getElementById('productList').value += customer + ","
document.getElementById('name1TXT').value = "";
}
Does anyone know why this would happen?
Edit
Here is all of my code.
<!DOCTYPE html>
<title></title>
<style>
.calcFrm {
}
</style>
<table style="width:300px;" border="1">
<tr>
<td>Customer Name</td>
<td><input type="text" id="name1TXT" /></td>
</tr>
<tr>
<td>Coating</td>
<td>
<select class="coating1DDL">
<option value="1">Galvanized</option>
<option value="2">Powder Coat</option>
<option value="3">None</option>
</select>
</td>
</tr>
<tr>
<td>Weight</td>
<td><input type="text" id="weight1TXT" onkeyup="sum1();"/></td>
</tr>
<tr>
<td>Length</td>
<td><input type="text" id="length1TXT" onkeyup="sum1();"/></td>
</tr>
<tr>
<td>Pieces</td>
<td><input type="text" id="pcs1TXT" onkeyup="sum1();"/></td>
</tr>
<tr>
<td>Pounds</td>
<td><input type="text" id="pounds1TXT" onkeyup="sum1();"readonly="readonly" /></td>
</tr>
<tr>
<td>Tons</td>
<td><input type="text" id="tons1TXT" onkeyup="convertPounds1();" readonly="readonly" /></td>
</tr>
</table>
<table style="width:300px;" border="1" class="tonsFrm2">
<tr>
<td>Customer Name</td>
<td><input type="text" id="name2TXT" /></td>
</tr>
<tr>
<td>Coating</td>
<td>
<select class="coating2DDL">
<option>Galvanized</option>
<option>Powder Coat</option>
<option>None</option>
</select>
</td>
</tr>
<tr>
<td>Weight</td>
<td><input type="text" id="weight2TXT" onkeyup="sum2();"/></td>
</tr>
<tr>
<td>Length</td>
<td><input type="text" id="length2TXT" onkeyup="sum2()"/></td>
</tr>
<tr>
<td>Pieces</td>
<td><input type="text" id="pcs2TXT" onkeyup="sum2();"/></td>
</tr>
<tr>
<td>Pounds</td>
<td><input type="text" id="pounds2TXT" readonly="readonly" onkeyup="sum2();" /></td>
</tr>
<tr>
<td>Tons</td>
<td><input type="text" id="tons2TXT" readonly="readonly" onkeyup="convertPounds2();" /></td>
</tr>
</table>
<table style="width:300px;" border="1" class="tonsFrm3">
<tr>
<td>Customer Name</td>
<td><input type="text" id="text3TXT" /></td>
</tr>
<tr>
<td>Coating</td>
<td>
<select class="coating3DDL">
<option>Galvanized</option>
<option>Powder Coat</option>
<option>None</option>
</select>
</td>
</tr>
<tr>
<td>Weight</td>
<td><input type="text" id="weight3TXT" onkeyup="sum3();"/></td>
</tr>
<tr>
<td>Length</td>
<td><input type="text" id="length3TXT" onkeyup="sum3();"/></td>
</tr>
<tr>
<td>Pieces</td>
<td><input type="text" id="pcs3TXT" onkeyup="sum3();"/></td>
</tr>
<tr>
<td>Pounds</td>
<td><input type="text" id="pounds3TXT" readonly="readonly" onkeyup="sum3();"/></td>
</tr>
<tr>
<td>Tons</td>
<td><input type="text" id="tons3TXT" readonly="readonly" onkeyup="convertPounds3();" /></td>
</tr>
</table>
<button onclick="transferData()">Submit</button>
<button type="reset" value="Reset">Reset</button>
<button type="button">Add New Form</button>
<br />
Pounds Total
<input type="text" id="TotalPoundsTxt" readonly="readonly" onkeyup="totalPounds();" />
Tons Total
<input type="text" id="TotalTonsTXT" readonly="readonly" onkeyup="totalTons();" />
<br />
<textarea rows="6" cols="50" id="productList">
</textarea>
<br />
<button type="button">Save Input</button>
Javascript:
//number correlate with form in order
//functions for first form
function sum1() {
var txtFirstNumberValue = document.getElementById('weight1TXT').value;
var txtSecondNumberValue = document.getElementById('length1TXT').value;
var txtThirdNumberValue = document.getElementById('pcs1TXT').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue) * parseInt(txtThirdNumberValue);
if (!isNaN(result)) {
document.getElementById('pounds1TXT').value = result;
}
}
function convertPounds1() {
var txtFirstNumberValue = document.getElementById('pounds1TXT').value;
var result = parseInt(txtFirstNumberValue) / 2000;
if (!isNaN(result)) {
document.getElementById('tons1TXT').value = result;
}
}
function galvCalc1() {
var galvOption = document.getElementById('').value
}
//functions for second form
function sum2() {
var txtFirstNumberValue = document.getElementById('weight2TXT').value;
var txtSecondNumberValue = document.getElementById('length2TXT').value;
var txtThirdNumberValue = document.getElementById('pcs2TXT').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue) * parseInt(txtThirdNumberValue);
if (!isNaN(result)) {
document.getElementById('pounds2TXT').value = result;
}
}
function convertPounds2() {
var txtFirstNumberValue = document.getElementById('pounds2TXT').value;
var result = parseInt(txtFirstNumberValue) / 2000;
if (!isNaN(result)) {
document.getElementById('tons2TXT').value = result;
}
}
//Functions for third form
function sum3() {
var txtFirstNumberValue = document.getElementById('weight3TXT').value;
var txtSecondNumberValue = document.getElementById('length3TXT').value;
var txtThirdNumberValue = document.getElementById('pcs3TXT').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue) * parseInt(txtThirdNumberValue);
if (!isNaN(result)) {
document.getElementById('pounds3TXT').value = result;
}
}
function convertPounds3() {
var txtFirstNumberValue = document.getElementById('pounds3TXT').value;
var result = parseInt(txtFirstNumberValue) / 2000;
if (!isNaN(result)) {
document.getElementById('tons3TXT').value = result;
}
}
function totalPounds(){
var firstpoundvalue = document.getElementById('pounds1TXT').value;
var secondpoundvalue = document.getElementById('pounds2TXT').value;
var thirdpoundvalue = document.getElementById('pounds3TXT').value;
var result = parseInt(firstpoundvalue) + parseInt(secondpoundvalue) + parseInt(thirdpoundvalue);
if (!isNaN(result)) {
document.getElementById('TotalPoundsTxt').value = result;
}
}
function totalTons() {
var firsttonvalue = document.getElementById('tons1TXT').value;
var secondtonvalue = document.getElementById('tons2TXT').value;
var thirdtonvalue = document.getElementById('tons3TXT').value;
var result = parseInt(firsttonvalue) + parseInt(secondtonvalue) + parseInt(thirdtonvalue);
if (!isNaN(result)) {
document.getElementById('TotalTonsTXT').value = result;
}
}
function transferData() {
var customer = document.getElementById("name1TXT").value;
if (customer != "")
document.getElementById('productList').value += customer + ",";
}
</script>
I cannot comment but I created as JSBin and seems to be working. I wasn't for sure how you are calling the transferData function to see the textarea clear so I just added an onBlur event to the input textbox.
I also added a semicolon to the line clearing the name1TXT value.
I still think everything is working regarding your code. By that I mean there aren't any odd bugs. But what exactly are you trying to accomplish? There appears to be 3 Customer Name boxes but when you click submit only 1 is being output into the textarea. It only grabs Customer1 and puts his/her name into the textarea and this process is repeating with each Submit. Are you trying to add all 3 customers? If so, then you will need more logic in your transferData function
you should use value like this
document.getElementById("writeArea").value = txt;
or like this in jQuery:
$('#myTextarea').val('');

OCR Web Validation using Javascript

I am a Computing teacher trying to stay one step ahead of my pupils whom are working on a assessment to with validating web forms using HTML and JavaScript. So far, I have managed to do the following but can no longer move forward:
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+='You must enter your name';
document.ExamEntry.name.focus();
document.getElementById("name").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+=' You must enter the subject';
document.ExamEntry.subject.focus();
document.getElementById("subject").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+=' You must enter the examination number';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000";
result = false;
}
if(document.getElementById("examnumber").value.length!=4)
{
msg+='You must have exactly 4 digits in the examination number textbox';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000"
result = false;
}
function checkRadio() {
var user_input = "";
var len = document.ExamEntry.entry.length;
var i;
for (i=0;i< len;i++) {
if (document.ExamEntry.entry[i].length.checked) {
user_input = document.ExamEntry.entry[i].value;
break;
}
}
if (msg==""){
return result;
}
else
{
alert(msg);
return result;
}
}
function resetForm()
{
document.getElementById('ExamEntry').reset();
document.getElementById("name").style.color="#000000";
document.getElementById("subject").style.color="#000000";
document.getElementById("examnumber").style.color="#000000";
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name='ExamEntry' method='post' action='success.html'>
<table width='50%' border='0'>
<tr>
<td id='name'>Name</td>
<td><input type='text' name='name' /></td>
</tr>
<tr>
<td id='subject'>Subject</td>
<td><input type='text' name='subject' /></td>
</tr>
<tr>
<td id='examnumber'>Examination Number</td>
<td><input type='text' name='examnumber'></td>
</tr>
<tr>
<td id='entry'>Level of Entry</td>
<td><input type='radio' name='entry' value='gcse'>GCSE<BR></td>
<td><input type='radio' name='entry' value='as'>AS<BR></td>
<td><input type='radio' name='entry' value='a2'>A2<BR></td>
</tr>
<tr>
<td><input type='submit' name='Submit' value='Submit' onclick='return (validateForm());'></td>
<td><input type='reset' name='Reset' value='Reset' onclick=' (resetForm());'></td>
</tr>
</table>
</form>
</body>
What I want to do and what I am trying to do are two different things and it's now hit the point where I am banging my head against a brick wall.
What I WANT to do is be able to:
Extend the Javascript code to make sure that the user’s examination number is exactly 4 digits.
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Can anyone help me before I totally lose the plot?
It's been a long time I have tried pure JS. It's a pleasure to try it out anytime though. So, someone's lukcy and I had some free time. I am a very tiny bit OCD when it comes to coding and I ended up cleaning a lot of your code, such as
Always enclose HTML attributes in double quotes - not a hard rule though.
Always close the input attributes - /> - not a hard rule though.
Define your elements and resue where needed in JS
Alwayst try and keep your JS separate from HTML - it's a good practice.
And follow the good old basics
As a result, here we go:
Demo: Fiddle
HTML:
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="#">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td id="entry">Level of Entry</td>
<td><input type="radio" name="entry" value="gcse" />GCSE<BR></td>
<td><input type="radio" name="entry" value="as" />AS<BR></td>
<td><input type="radio" name="entry" value="a2" />A2<BR></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" onclick="resetForm();"></td>
</tr>
</table>
</form>
JS:
var form = document.forms['ExamEntry'];
var iName = form.elements['name'];
var iSubject = form.elements['subject'];
var iExamNumber = form.elements['examnumber'];
var iLevel = form.elements['entry'];
function validateForm() {
var result = true;
var msg = "";
if (iName.value=="") {
msg+='You must enter your name';
iName.focus();
iName.style.color="#FF0000";
result = false;
} else if (iSubject.value=="") {
msg+=' You must enter the subject';
iSubject.focus();
iSubject.style.color="#FF0000";
result = false;
} else if (iExamNumber.value=="" || !/^\d{4}$/.test(iExamNumber.value)) {
msg+=' You must enter a valid examination number';
iExamNumber.focus();
iExamNumber.style.color="#FF0000";
result = false;
} else if(!checkEntry()) {
msg+=' You must select a level';
result = false;
} else {
var cfm = confirm("You have selected " + checkEntry() + ". Are you sure to punish yourself?");
if (!cfm) {
result = false;
}
}
if (!result && msg != "") alert (msg);
return result;
}
function checkEntry() {
for (var i=0; i<iLevel.length; i++) {
if (iLevel[i].checked) {
return iLevel[i].value.toUpperCase();
}
}
return false;
}
function resetForm() {
form.reset();
iName.style.color="#000000";
iSubject.style.color="#000000";
iExamNumber.style.color="#000000";
}
form.onsubmit = validateForm;
form.onreset = resetForm;
First you added the function checkRadio inside of function validateForm
Also, this line
if(document.getElementById("examnumber").value.length!=4)
actually points to this piece of html
<td id='examnumber'>Examination Number</td>
The td element can't hold values... You need to change the line to this:
if (document.ExamEntry.examnumber.value.length!=4) {
This jsfiddle should help you out...

Categories