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('');
Related
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
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));
This is a simple multiplication calculator which on typing automatically adds comma to separate groups of thousands. However it doesn't accept decimal value for example 1,778.23. Copy pasting it directly into the field works but can't type it. Any solution would be much appreciated.
function calculate() {
var myBox1 = updateValue('box1');
var myBox2 = updateValue('box2');
var myResult = myBox1 * myBox2;
adTextRes('result', myResult)
}
function updateValue(nameOf) {
var inputNo = document.getElementById(nameOf).value;
var no = createNo(inputNo);
adTextRes(nameOf, no);
return no;
}
function adTextRes(nameOf, no) {
var asText = String(no).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById(nameOf).value = asText;
}
function createNo(textin) {
return Number(textin.replace(/,/g, ""));
}
<table width="80%" border="0">
<tr>
<th>Box 1</th>
<th>Box 2</th>
<th>Result</th>
</tr>
<tr>
<td><input id="box1" type="text" oninput="calculate()" /></td>
<td><input id="box2" type="text" oninput="calculate()" /></td>
<td><input id="result" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
The problem is, in createNo:
return Number(textin.replace(/,/g, ""));
A trailing period will just get discarded when converted to a Number. There's no need for such a casting in the first place, though - just leave it off, and it'll work as expected:
function createNo(textin) {
return textin.replace(/,/g, "");
}
To prevent multiple decimal points from being entered, you can use another replace in the same function:
.replace(/(\.\d*)\./, '$1')
function calculate() {
var myBox1 = updateValue('box1');
var myBox2 = updateValue('box2');
var myResult = myBox1 * myBox2;
adTextRes('result', myResult)
}
function updateValue(nameOf) {
var inputNo = document.getElementById(nameOf).value;
var no = createNo(inputNo);
adTextRes(nameOf, no);
return no;
}
function adTextRes(nameOf, no) {
var asText = String(no).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById(nameOf).value = asText;
}
function createNo(textin) {
return textin
.replace(/,/g, "")
.replace(/(\.\d*)\./, '$1')
}
<table width="80%" border="0">
<tr>
<th>Box 1</th>
<th>Box 2</th>
<th>Result</th>
</tr>
<tr>
<td><input id="box1" type="text" oninput="calculate()" /></td>
<td><input id="box2" type="text" oninput="calculate()" /></td>
<td><input id="result" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
I am in the process of writing a webpage. I have everything done that is needed, however, when you enter any quantity over 30 it will make the id = "shipping" color red. It does this but it does it for anything less than 30 as well. Also I am having trouble with my submit button sending off to a server/url. Any help is appreciated! I will attach my code!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Widgets R' Us </title>
<style>
table,
td {
border: 1px solid black;
}
</style>
<script type="text/javascript">
//Check if non -number or a negative number
function realNumber() {
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
//isNaN is a predetermined function
if ((isNaN(qty1) || qty1 < 0) || (isNaN(qty2) || qty2 < 0) || (isNaN(qty3) || qty3 < 0)) {
alert("The quantity given is not a real number or is a negative number!");
return false; //Will not allow for data to go to server.
} else {
return true;
}
}
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
} else {
document.getElementById("shipping").style.color = "black";
}
}
}
function checkOut() {
if (total()) {
if ((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked)) {
return true;
}
}
return false;
}
</script>
</head>
<body>
<div>
<h1><b><big> Widgets R' Us </b></strong>
</h1>
<h2><b> Order/Checkout </b></h2>
<form name "widgets" onsubmit="return checkOut();" action="https://www.reddit.com/" method="get">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" /</td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" /</td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Product Total:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()" /> </td>
</tr>
</form>
</body>
</html>
Problem with your values qty1,qty2,qty3. these values are reading as string. so instead of addding these values , its concatinating the strings. replace
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
with
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
It will Solve your problem with 'Red'.
For the submit button, function total() is not returning anything. so change something like
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
return true;
} else if(over>0) {
document.getElementById("shipping").style.color = "black";
return true;
}else{
document.getElementById("shipping").style.color = "black";
return false;
}
}
}
and checkout() as
function checkOut() {
if (total()) {
if (((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked))||
(document.getElementById("shipping").style.color != "red")) {
return true;
}
}
return false;
}
Replace
var over = qty1 + qty2 + qty3;
With
var over = parseInt(qty1) + parseInt(qty2) + parseInt(qty3);
There were some minor HTML errors but the real issue is that numeric strings were being concatenated. So, to get the quantity values you need to use parseInt() to extract the integer value so that math is performed instead of string concatenation. Also, it's a little odd that the user has to click the Calculate Button in order to see a total. The button does work correctly, but is this what you really want?
One more thing, as tempting as it may be to directly alter the color of elements with JavaScript, in terms of keeping the code more robust, it is preferable to simply change the class name as the code does in this example since I created two classes in the CSS for this purpose.
The form now submits as long as the checkbox is unchecked and the units do not exceed 30. I changed the method to "post" and adjusted the true/false return statements in checkOut(). Note when data is submitted using the POST method, then no form data appears appended to the URL; for more info see here. I also altered the totals() function so that now it returns a value, namely the total price.
var d = document;
d.g = d.getElementById;
var qty = [0, 0, 0, 0];
var shipping = d.g("shipping");
function realNumber() {
var qtyInvalid = [0, 0, 0, 0];
for (let i = 1, max = qtyInvalid.length; i < max; i++) {
qtyInvalid[i] = (isNaN(qty[i]) || qty[i] < 0);
}
if (qtyInvalid[1] || qtyInvalid[2] || qtyInvalid[3]) {
console.log("The quantity given is not a real number or is a negative number!");
return false;
}
return true;
}
function total() {
var over = 0;
var price = [0, 0, 0, 0];
for (j = 1, max = price.length; j < max; j++) {
price[j] = d.g("Price" + j + "").value;
qty[j] = d.g("Quantity" + j + "").value;
}
var totals = 0;
var yes = 0;
const radix = 10;
for (q = 1, max = qty.length; q < max; q++) {
over += parseInt(qty[q], radix)
}
//console.log(over);
if (!realNumber()) {
return false;
}
for (let k = 1, max2 = price.length; k < max2; k++) {
totals += (price[k] * qty[k]);
}
yes = (totals).toFixed(2);
d.g("ProductTotal").innerHTML = "$" + yes;
shipping.className = (over > 30) ? "red" : "black";
return totals;
} // end total
function checkOut() {
var retval = false;
var shippingIsRed = (shipping.className == "red");
var extraChecked = d.g("extra").checked;
if ( total() ) {
retval = (!shippingIsRed && !extraChecked)? true : false;
}
return retval;
} //end checkout
h1 {
font: 200% Arial, Helvetica;
font-weight: bold;
}
h2 {
font-weight: bold;
}
table,
td {
border: 1px solid black;
}
p.red {
color: #f00;
}
p.black {
color: #000;
}
<div>
<h1>Widgets R' Us</h1>
<h2>Order/Checkout</h2>
<form name="widgets" onsubmit="return checkOut()" action="https://www.example.com/" method="post">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" </td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" </td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Total Price:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping" class="black">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()"> </td>
</tr>
</form>
I also removed some unnecessary repetitive code that fetches the quantity values, taking advantage of JavaScript closures and for-loops.
I have a table which has one row in which I multiply two fields, namely quantity and rate/quantity, to get the product total. I have provided a button to add a new row which basically clones the 1st row. Now I want the cloned row to also have the same product as the 1st row. I have tried the following code:
<!DOCTYPE html>
<html>
<h3 align="center">K J Somaiya College Of Engineering, Vidyavihar, Mumbai-400 077</h3>
<h3 align="center">Department Of Information Technology</h3>
<body>
<script>
function WO1() {
var qty = document.getElementById('qty').value;
var price = document.getElementById('price').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice').value = answer;
}
function WO2() {
var qty = document.getElementById('qty1').value;
var price = document.getElementById('price1').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice1').value = answer;
}
function WO3() {
var qty = document.getElementById('qty2').value;
var price = document.getElementById('price2').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice2').value = answer;
}
</script>
<script>
function validateNumbe()
{
var x=document.getElementById("floor").value;
if (x==null || x=="")
{
alert("Floor must be entered");
return false;
}
}
function validateN()
{
var x=document.getElementById("lab").value;
if (x==null || x=="")
{
alert("Laboratory Name must be entered");
return false;
}
}
function validateNumb()
{
var x=document.getElementById("room").value;
if (x==null || x=="")
{
alert("Room No must be entered");
return false;
}
}
function validateNum()
{
var x=document.getElementById("labi").value;
if (x==null || x=="")
{
alert("Name of Laboratory Incharge must be entered");
return false;
}
}
function validateNu()
{
var x=document.getElementById("year").value;
if (x==null || x=="")
{
alert("Budget for the year must be entered");
return false;
}
}
</script>
<table width="100%" cellspacing="10">
<tr>
<td align="left">Date:<input type="date" name="date"/></td>
<td align="right">Floor: <input type="text" id="floor" onchange="validateNumbe()"
onblur="validateNumbe()"/> </td>
</tr>
<tr>
<td align="left">Laboratory Name: <input type="text" id="lab" onchange="validateN()"
onblur="validateN()"/></td>
<td align="right">Room no: <input type="text" id="room" onchange="validateNumb()"
onblur="validateNumb()"/></td>
</tr>
<tr>
<td align="left">Name of Laboratory Incharge: <input type="text" id="labi"
onchange="validateNum()" onblur="validateNum()"/></td>
<td align="right">Budget for the year: <input type="text" id="year" onchange="validateNu()"
onblur="validateNu()"/></td>
</tr>
</table>
<h3 align="left"><b>Computer</b><h3>
<table id="POITable" border="1" width="100%">
<tr>
<td style="width:10%">Sr No.</td>
<td>Item Description</td>
<td>Quantity</td>
<td>Rate(Inclusive of Taxes)</td>
<td>Total Cost</td>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price' class="price" placeholder='Price (£)'
onChange="WO1()" /></td>
<td><input type='text' name='Total' id='totalprice' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton" value="Add New Row"/>
<h3 align="left"><b>Equipment</b><h3>
<table id="POITable1" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty1' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price1' class="price" placeholder='Price (£)'
onChange="WO2()" /></td>
<td><input type='text' name='Total' id='totalprice1' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton1" value="Add New Row"/>
<h3 align="left"><b>Furniture</b><h3>
<table id="POITable2" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty2' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price2' class="price" placeholder='Price (£)'
onChange="WO3()" /></td>
<td><input type='text' name='Total' id='totalprice2' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton2" value="Add New Row"/>
<script>
( function() { // Prevent vars from leaking to the global scope
var formTable = document.getElementById('POITable');
var newRowBtn = document.getElementById('addmorePOIbutton');
newRowBtn.addEventListener('click', insRow, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow() {
var new_row = formTable.rows[1].cloneNode(true),
numTableRows = formTable.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable.appendChild( new_row );
}
var formTable1 = document.getElementById('POITable1');
var newRowBtn1 = document.getElementById('addmorePOIbutton1');
newRowBtn1.addEventListener('click', insRow1, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow1() {
var new_row = formTable1.rows[1].cloneNode(true),
numTableRows = formTable1.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable1.appendChild( new_row );
}
var formTable2 = document.getElementById('POITable2');
var newRowBtn2 = document.getElementById('addmorePOIbutton2');
newRowBtn2.addEventListener('click', insRow2, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow2() {
var new_row = formTable2.rows[1].cloneNode(true),
numTableRows = formTable2.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable2.appendChild( new_row );
}
})();
function myfun()
{
var lun= document.getElementById('POITable').rows.length;
document.getElementsByName("len")[0].value = lun-1;
var lun1= document.getElementById('POITable1').rows.length;
document.getElementsByName("len1")[0].value = lun1-1;
var lun2= document.getElementById('POITable2').rows.length;
document.getElementsByName("len2")[0].value = lun2-1;
}
function myFunction()
{
window.print();
}
</script>
<input type="hidden" name="len" value="1">
<input type="hidden" name="len1" value="1">
<input type="hidden" name="len2" value="1">
<table width="100%">
<tr>
<td><br><br><br></td>
<td><br><br><br></td>
<td><br><br><br></td>
</tr>
<tr>
<td align="left">Signature <br>Lab-In-Charge</td>
<td align="center">Signature<br>Lab Assistant</td>
<td align="right">Signature <br>Head of Department</td>
</tr>
</table>
<br><br><br>
<input type="submit" value="SUBMIT" onclick='this.form.action="archive.php";myfun();'>
<input type="submit" value="SAVE AND CONTINUE LATER"
onclick='this.form.action="myphpformhandler.php";myfun();'>
</form>
<h3 align="center"><button onclick="myFunction()"><h3>Print this page</h3></button></h3>
</body>
</html>
i have created the JSFiddle but the multiplication is not working in it.
http://jsfiddle.net/xkY4Z/2/
Not a perfect solution to your problem but a bit closer Working Fiddle
Done using jQuery
$(document).on('change','input', function () {
var id = $(this).attr('id').split("-");
var answer = (Number($('#qty-' + id[1]).val()) * Number($('#price-' + id[1]).val())).toFixed(2);
$('#totalprice-' + id[1]).val(answer);
});
Update
Working Fiddle with name
Latest
Fiddle with Grand total