Can’t identify object attribute: Uncaught ReferenceError: fat is not defined - javascript

I’m building a simple application to calculate BMI as part of an JS exercise and can’t get past this error when I create an object to read inputs of my form. The error I get is the one in the title. Uncaught ReferenceError: fat is not defined at HTMLButtonElement.
var button = document.querySelector("#button-add");
button.addEventListener("click", function() {
event.preventDefault();
var form = document.querySelector("#add-form");
var patient = getFormPatient
console.log(patient);
var patientTr = document.createElement("tr");
var nameTd = document.createElement("td");
var weightTd = document.createElement("td");
var heightTd = document.createElement("td");
var fatTd = document.createElement("td");
var bmiTd = document.createElement("td");
nameTd.textContent = name;
weightTd.textContent = weight;
heightTd.textContent = height;
fatTd.textContent = fat;
bmiTd.textContent = calculateBmi(weight, height);
patientTr.appendChild(nameTd);
patientTr.appendChild(weightTd);
patientTr.appendChild(heightTd);
patientTr.appendChild(fatTd);
patientTr.appendChild(bmiTd);
var table = document.querySelector("#patients-table");
table.appendChild(patientTr);
})
function getFormPatient(form) {
var patient = {
name: form.name.value,
weight: form.weight.value,
fat: form.fat.value,
height: form.height.value
}
return patient;
}
<header>
<div class="container">
<h1 class="title">Queensland Nutrition</h1>
</div>
</header>
<main>
<section class="container">
<h2>My clients</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Weight(kg)</th>
<th>Height(m)</th>
<th>Fat Percentage (%)</th>
<th>BMI</th>
</tr>
</thead>
<tbody id="patients-table">
<tr class="patients">
<td class="info-name">Paulo</td>
<td class="info-weight">100</td>
<td class="info-height">2.00</td>
<td class="info-fat">10</td>
<td class="info-bmi">0</td>
</tr>
<tr class="patients">
<td class="info-name">João</td>
<td class="info-weight">80</td>
<td class="info-height">1.72</td>
<td class="info-fat">40</td>
<td class="info-bmi">0</td>
</tr>
<tr class="patients">
<td class="info-name">Erica</td>
<td class="info-weight">54</td>
<td class="info-height">1.64</td>
<td class="info-fat">14</td>
<td class="info-bmi">0</td>
</tr>
<tr class="patients">
<td class="info-name">Douglas</td>
<td class="info-weight">85</td>
<td class="info-height">1.73</td>
<td class="info-fat">24</td>
<td class="info-bmi">0</td>
</tr>
<tr class="patients">
<td class="info-name">Tatiana</td>
<td class="info-weight">46</td>
<td class="info-height">1.55</td>
<td class="info-fat">19</td>
<td class="info-bmi">0</td>
</tr>
</tbody>
</table>
</section>
<section class="container">
<h2 id="titulo-form">Add New Patient</h2>
<form id="add-form">
<div class="grupo">
<label for="nome">Name:</label>
<input id="nome" name="name" type="text" placeholder="enter patient's name" class="campo">
</div>
<div class="grupo">
<label for="peso">Weight:</label>
<input id="peso" name="weight" type="text" placeholder="enter patient's weight" class="campo campo-medio">
</div>
<div class="grupo">
<label for="altura">Height:</label>
<input id="altura" name="height" type="text" placeholder="enter patient's height" class="campo campo-medio">
</div>
<div class="grupo">
<label for="gordura">Fat Percentage:</label>
<input id="gordura" name="fat" type="text" placeholder="enter patient's fat percentage" class="campo campo-medio">
</div>
<button id="button-add" class="botao bto-principal">Adicionar</button>
</form>
</section>
</main>
<script src="js/bmi-calc.js" type="text/javascript"></script>
<script src="js/form.js" type="text/javascript"></script>
I thought I might be making a mistake with variable names, but reviewed them and can’t find any. Any ideas on what I’m doing wrong here?
------------------------- EDIT ---------------------
adding code for the calculateBmi function to make it clearer. That's literally all the code I have for the exercise.
var patients = document.querySelectorAll(".patients");
function calculateBmi(weight, height) {
var bmi = 0;
bmi = weight / (height * height);
return bmi.toFixed(2);
}
for (var i = 0; i < patients.length; i++) {
var patient = patients[i];
var tdWeight = patient.querySelector(".info-weight");
var weight = tdWeight.textContent;
var tdHeight = patient.querySelector(".info-height");
var height = tdHeight.textContent;
var tdBmi = patient.querySelector(".info-bmi");
var validWeight = true;
var validHeight = true;
if (weight <= 0 || weight >= 700) {
validWeight = false;
tdBmi.textContent = "Invalid weight";
patient.classList.add("invalid-patient");
}
if (height <= 0 || height >= 3) {
validHeight = false;
tdBmi.textContent = "Invalid height";
patient.classList.add("invalid-patient");
}
if (validHeight == true && validWeight == true) {
var bmi = calculateBmi(weight, height);
tdBmi.textContent = bmi;
}
}

You have no variables name, weight, height, or fat. I think you meant patient.name, etc.
But you didn't call the function in
var patient = getFormPatient
You need parentheses with the argument after it.
var button = document.querySelector("#button-add");
button.addEventListener("click", function() {
event.preventDefault();
var form = document.querySelector("#add-form");
var patient = getFormPatient(form);
console.log(patient);
var patientTr = document.createElement("tr");
var nameTd = document.createElement("td");
var weightTd = document.createElement("td");
var heightTd = document.createElement("td");
var fatTd = document.createElement("td");
var bmiTd = document.createElement("td");
nameTd.textContent = patient.name;
weightTd.textContent = patient.weight;
heightTd.textContent = patient.height;
fatTd.textContent = patient.fat;
bmiTd.textContent = calculateBmi(patient.weight, patient.height);
patientTr.appendChild(nameTd);
patientTr.appendChild(weightTd);
patientTr.appendChild(heightTd);
patientTr.appendChild(fatTd);
patientTr.appendChild(bmiTd);
var table = document.querySelector("#patients-table");
table.appendChild(patientTr);
})
function getFormPatient(form) {
var patient = {
name: form.name.value,
weight: form.weight.value,
fat: form.fat.value,
height: form.height.value
}
return patient;
}
<header>
<div class="container">
<h1 class="title">Queensland Nutrition</h1>
</div>
</header>
<main>
<section class="container">
<h2>My clients</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Weight(kg)</th>
<th>Height(m)</th>
<th>Fat Percentage (%)</th>
<th>BMI</th>
</tr>
</thead>
<tbody id="patients-table">
<tr class="patients">
<td class="info-name">Paulo</td>
<td class="info-weight">100</td>
<td class="info-height">2.00</td>
<td class="info-fat">10</td>
<td class="info-bmi">0</td>
</tr>
<tr class="patients">
<td class="info-name">João</td>
<td class="info-weight">80</td>
<td class="info-height">1.72</td>
<td class="info-fat">40</td>
<td class="info-bmi">0</td>
</tr>
<tr class="patients">
<td class="info-name">Erica</td>
<td class="info-weight">54</td>
<td class="info-height">1.64</td>
<td class="info-fat">14</td>
<td class="info-bmi">0</td>
</tr>
<tr class="patients">
<td class="info-name">Douglas</td>
<td class="info-weight">85</td>
<td class="info-height">1.73</td>
<td class="info-fat">24</td>
<td class="info-bmi">0</td>
</tr>
<tr class="patients">
<td class="info-name">Tatiana</td>
<td class="info-weight">46</td>
<td class="info-height">1.55</td>
<td class="info-fat">19</td>
<td class="info-bmi">0</td>
</tr>
</tbody>
</table>
</section>
<section class="container">
<h2 id="titulo-form">Add New Patient</h2>
<form id="add-form">
<div class="grupo">
<label for="nome">Name:</label>
<input id="nome" name="name" type="text" placeholder="enter patient's name" class="campo">
</div>
<div class="grupo">
<label for="peso">Weight:</label>
<input id="peso" name="weight" type="text" placeholder="enter patient's weight" class="campo campo-medio">
</div>
<div class="grupo">
<label for="altura">Height:</label>
<input id="altura" name="height" type="text" placeholder="enter patient's height" class="campo campo-medio">
</div>
<div class="grupo">
<label for="gordura">Fat Percentage:</label>
<input id="gordura" name="fat" type="text" placeholder="enter patient's fat percentage" class="campo campo-medio">
</div>
<button id="button-add" class="botao bto-principal">Adicionar</button>
</form>
</section>
</main>
<script src="js/bmi-calc.js" type="text/javascript"></script>
<script src="js/form.js" type="text/javascript"></script>

Your object patient has all the params,
so use patient.field_name to get the value.
var button = document.querySelector("#button-add");
button.addEventListener("click", function() {
event.preventDefault();
var addForm = document.querySelector("#add-form");
var patient = getFormPatient(addForm)
console.log(patient);
var patientTr = document.createElement("tr");
var nameTd = document.createElement("td");
var weightTd = document.createElement("td");
var heightTd = document.createElement("td");
var fatTd = document.createElement("td");
var bmiTd = document.createElement("td");
nameTd.textContent = patient.name;
weightTd.textContent = patient.weight;
heightTd.textContent = patient.height;
fatTd.textContent = patient.fat;
bmiTd.textContent = calculateBmi(weight, height);
patientTr.appendChild(nameTd);
patientTr.appendChild(weightTd);
patientTr.appendChild(heightTd);
patientTr.appendChild(fatTd);
patientTr.appendChild(bmiTd);
var table = document.querySelector("#patients-table");
table.appendChild(patientTr);
})
function getFormPatient(form) {
var patient = {
name: form.name.value,
weight: form.weight.value,
fat: form.fat.value,
height: form.height.value
}
console.log(patient);
return patient;
}

Related

Why the text generated from the previous table row of number cannot be displayed in the next table row?

Here's another problem encountered with js/html code. I typed some numbers at the top of the page, then after I pressed the button First Line, it will display the numbers I inputted in the first table row accordingly. If I press the button Last Line, I'd like it to display some numbers after getting done with some arithmetics, which is in the btn2 part in the js file, in the last table row of the page. I'd like to find out if it is the problem of innerHTML or valueAsNumber in the if statements, or the variables declared in the for loop not applicable in the later if statements, that caused the numbers in the last row cannot be displayed eventually.
The for loop and the if statement is intended for the page to scan the numbers inputted in the first row, do some arithmetics with them, and display them in the last row, in each respective cell. Is there any other way out to do so?
Thank you very much!
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
var R1 = [R1C1, R1C2, R1C3, R1C4, R1C5, R1C6, R1C7, R1C8,
R1C9, R1C10, R1C11, R1C12, R1C13, R1C14, R1C15, R1C16];
var R2 = [R2C1, R2C2, R2C3, R2C4, R2C5, R2C6, R2C7, R2C8,
R2C9, R2C10, R2C11, R2C12, R2C13, R2C14, R2C15, R2C16];
btn1.addEventListener('click', () => {
for (var i = 0; i <= 15; i++) {
let row = tab.rows[1];
let c = row.cells[i];
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
btn2.addEventListener('click', () => {
for (var i = 0; i <= 15; i++) {
var r1c = R1[i].id;
var r2c = R2[i].id;
var r1El = document.getElementById(r1c);
var r2El = document.getElementById(r2c);
}
if (r1El.innerHTML > 0) {
var choices = [0, (r1El.valueAsNumber) % 7, (r1El.valueAsNumber + 2) % 7, (r1El.valueAsNumber - 2) % 7];
var x = Math.floor(Math.random() * choices.length);
if (choices[x] == choices.at(0)) {
r2El.innerHTML = choices[x];
} else if (choices[x] <= 0) {
r2El.innerHTML = choices[x] + 7;
}
}
});
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
text-align: center;
}
<div class="container">
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
<td id="inpb3">Group 3</td>
<td id="inpb4">Group 4</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
<td>
<input type="number" id="inp9" title="inp9">
<input type="number" id="inp10" title="inp10">
<input type="number" id="inp11" title="inp11">
<input type="number" id="inp12" title="inp12">
</td>
<td>
<input type="number" id="inp13" title="inp13">
<input type="number" id="inp14" title="inp14">
<input type="number" id="inp15" title="inp15">
<input type="number" id="inp16" title="inp16">
</td>
</tr>
</table>
<br>
<button id="btn1">First line</button>
<button id="btn2">Last line</button>
</div>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
<th colspan="4">Group 3</th>
<th colspan="4">Group 4</th>
</tr>
<tr>
<td id="R1C1"></td>
<td id="R1C2"></td>
<td id="R1C3"></td>
<td id="R1C4"></td>
<td id="R1C5"></td>
<td id="R1C6"></td>
<td id="R1C7"></td>
<td id="R1C8"></td>
<td id="R1C9"></td>
<td id="R1C10"></td>
<td id="R1C11"></td>
<td id="R1C12"></td>
<td id="R1C13"></td>
<td id="R1C14"></td>
<td id="R1C15"></td>
<td id="R1C16"></td>
</tr>
<tr>
<td id="R2C1"></td>
<td id="R2C2"></td>
<td id="R2C3"></td>
<td id="R2C4"></td>
<td id="R2C5"></td>
<td id="R2C6"></td>
<td id="R2C7"></td>
<td id="R2C8"></td>
<td id="R2C9"></td>
<td id="R2C10"></td>
<td id="R2C11"></td>
<td id="R2C12"></td>
<td id="R2C13"></td>
<td id="R2C14"></td>
<td id="R2C15"></td>
<td id="R2C16"></td>
</tr>
</table>
</div>
So you can Iterate the td by iterating the elements HTMLCollection property of the tr. Iterate two Iterables by using the index from one.
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const firstRow = tab.firstElementChild.children[1].children;
const secondRow = tab.firstElementChild.children[2].children;
btn1.addEventListener('click', () => {
for (var i = 0; i <= 7 /* <- This is a magic value - avoid these */; i++) {
let row = tab.rows[1];
let c = row.cells[i];
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
btn2.addEventListener('click', () => {
[...secondRow].forEach((el,index)=>{
//let group = Math.floor(index / 4);
let inp = parseInt(firstRow[index].innerText, 10);
if (!inp) return;
let choices = [0, inp, (inp + 2), (inp - 2)];
let x = (Math.floor(Math.random() * choices.length) + 7) % 7;
el.innerText = x;
})
});
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
height: 1.5em;
text-align: center;
}
<div class="container">
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
</tr>
</table>
<br>
<button id="btn1">First line</button>
<button id="btn2">Last line</button>
</div>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
</tr>
</table>
</div>
Some additional advice:
I couldn't be bothered to clean up all of your code, next time please provide a Minimal Example, tree fields would have been plenty to ask the question.
Further please avoid magic numbers, like you use in your loops. Get the size of what you are iterating when you use it. This makes your code more flexible and reusable.
In the same vein: Please do not throw ids everywhere. They just beg to break your code if you ever try to reuse it somehow.

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.

Error within HTML Code

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.

How to enable/disable a row with checkbox?

I am trying to do a form, when you click on checkbox it has to enables the rows of the form, but it's not working...
For example, there's a checkbox above the by clicking it, it has to enable the rest of rows
I'll appreciate any help,
Thanks in advance.
Here is what I have:
<HTML>
<HEAD>
<TITLE>Online Shopping</TITLE>
<SCRIPT>
//Variables Globales
var RowsInForm = 4
var ProductsInList = 4
var SalesTaxRate = 0.12
var TaxableState = "IVA(12%)"
var ProdSubscript = 0
function MakeArray(n) {
this.length = n
for (var i = 1; i<= n; i++) {
this[i] = 0
}
return this
}
function BuildZeroArray(n) {
this.length = n
for (var i = 0; i<= n; i++) {
this[i] = 0
}
return this
}
function prodobj(name, unitprice) {
this.name = name
this.unitprice = unitprice
}
function ordobj(prodsub, qty, unitprice, extprice) {
this.prodsub = prodsub
this.qty = qty
this.unitprice = unitprice
this.extprice = extprice
}
function strToZero(anyval) {
anyval = ""+anyval
if (anyval.substring(0,1) < "0" || anyval.substring(0,1) > "9") {
anyval = "0"
}
return eval(anyval)
}
function updateRow(rownum){
var exec = 'ProdSubscript = document.ordform.prodchosen'+rownum+'.selectedIndex'
eval (exec)
ordData[rownum].prodsub=ProdSubscript
var exec='tempqty=document.ordform.qty'+rownum+'.value'
eval (exec)
ordData[rownum].qty = strToZero(tempqty)
ordData[rownum].unitprice=prodlist[ProdSubscript].unitprice
ordData[rownum].extprice = (ordData[rownum].qty) * ordData[rownum].unitprice
var exec = 'document.ordform.unitprice'+rownum+'.value = currencyPad(ordData['+rownum+'].unitprice,10)'
eval (exec)
var exec = 'document.ordform.extprice'+rownum+'.value = currencyPad(ordData['+rownum+'].extprice,10)'
eval (exec)
updateTotals()
}
function updateTotals() {
var subtotal = 0
for (var i=1; i<=RowsInForm; i++) {
subtotal = subtotal + ordData[i].extprice
}
document.ordform.subtotal.value = currencyPad(subtotal,10)
salestax = 0
if (document.ordform.Taxable.checked) {
salestax = SalesTaxRate * subtotal * 0.30
}
document.ordform.salestax.value = currencyPad(salestax,10)
document.ordform.grandtotal.value = currencyPad(subtotal+salestax,10)
}
function copyAddress() {
document.ordform.ShipName.value = document.ordform.billName.value
document.ordform.ShipCompany.value = document.ordform.billCompany.value
document.ordform.ShipAdd1.value = document.ordform.billAdd1.value
document.ordform.ShipAdd2.value = document.ordform.billAdd2.value
document.ordform.ShipCSZ.value = document.ordform.billCSZ.value
}
function currencyPad(anynum,width) {
//returns number as string in $xxx,xxx.xx format.
anynum = "" + eval(anynum)
//evaluate (in case an expression sent)
intnum = parseInt(anynum)
//isolate integer portion
intstr = ""+intnum
//add comma in thousands place.
if (intnum >= 1000) {
intlen = intstr.length
temp1=parseInt(""+(intnum/1000))
temp2=intstr.substring(intlen-3,intlen)
intstr = temp1+","+temp2
}
if (intnum >= 1000000) {
intlen = intstr.length
temp1=parseInt(""+(intnum/1000000))
temp2=intstr.substring(intlen-7,intlen)
intstr = temp1+","+temp2
}
decnum = Math.abs(parseFloat(anynum)-parseInt(anynum)) //isolate decimal portion
decnum = decnum * 100 // multiply decimal portion by 100.
decstr = "" + Math.abs(Math.round(decnum))
while (decstr.length < 2) {
decstr += "0"
}
retval = intstr + "." + decstr
if (intnum < 0) {
retval=retval.substring(1,retval.length)
retval="("+retval+")"
}
retval = "BsF"+retval
while (retval.length < width){
retval=" "+retval
}
return retval
}
</SCRIPT>
</HEAD>
<BODY aLink=#8a8a8a bgColor=#ffffff
link=#ff0000 text=#000000 vLink=#215e21>
<H3 align=center><FONT color=#0000ff><FONT size=+1></FONT></FONT></H3>
<P><BR>
<SCRIPT>
//Create a new array named prodlist with six elements.
prodlist = new BuildZeroArray(ProductsInList) //Refers to global variable ProductsInList
//Populate that array with this product info.
//The first item, prodlist[0] must be a "non-product" with
//a unitprice of zero.
prodlist[0] = new prodobj('-none-',0)
prodlist[1] = new prodobj('Apple iPhone ',5200)
prodlist[2] = new prodobj('Pc Laptop',3520)
prodlist[3] = new prodobj('Impresora',4790)
prodlist[4] = new prodobj('TV',8650)
//Create a new array, named ordData, that contains empty Order Objects.
ordData = new MakeArray(RowsInForm)
for (var i=1; i<= RowsInForm; i++) {
ordData[i] = new ordobj(0,0,0,0)}
</SCRIPT>
<FORM name=ordform></P>
<CENTER>
<P><! Display the table header></P></CENTER>
<TABLE align=center border=1>
<CENTER>
<TBODY>
<TR>
<TH width=192>
<CENTER><B>Product</B></CENTER></TH>
<TH width=72>
<CENTER><B>Qty</B></CENTER></TH>
<TH width=120>
<CENTER><B>Unit Price</B></CENTER></TH>
<TH width=120>
<CENTER><B>Ext Price</B></CENTER></TH>
<P><INPUT type=checkbox value=true>
<SCRIPT>
for (var rownum = 1;rownum <= RowsInForm; rownum++) {
document.write('<TR><TD WIDTH=192>')
document.write('<SELECT NAME="prodchosen'+rownum+'" onChange= "updateRow('+rownum+')">')
for (i = 0; i <= ProductsInList; i++) {
document.write ("<OPTION>"+prodlist[i].name)
} document.write ('</SELECT>')
document.write ('</TD><TD WIDTH=72><CENTER><INPUT NAME="qty'+rownum+'" VALUE=""')
document.write ('MAXLENGTH="3" SIZE=3 onChange="updateRow('+rownum+')"></CENTER>')
document.write ('</TD><TD WIDTH=120><CENTER>')
document.write ('<INPUT NAME="unitprice'+rownum+'" VALUE="" MAXLENGTH="10"')
document.write ('SIZE=10 onfocus="this.blur()"></CENTER>')
document.write ('</TD><TD WIDTH=120><CENTER>')
document.write ('<INPUT NAME="extprice'+rownum+'" VALUE="" MAXLENGTH="10"')
document.write ('SIZE=10 onfocus = "this.blur()"></CENTER>')
document.write ('</TD></TR>')
}
</SCRIPT>
<P></P></CENTER></TBODY></TABLE>
<CENTER>
<P><! Second table holds subtotal, sales tax, grand total></P></CENTER>
<TABLE>
<TBODY>
<TR>
<TD width=264></TD>
<TD width=120>
<CENTER>
<P>Subtotal: </P></CENTER></TD>
<TD width=120>
<CENTER>
<P><INPUT maxLength=10 name=subtotal onfocus=this.blur()
size=10></P></CENTER></TD></TR>
<TR>
<TD width=264>
<P><INPUT name=Taxable onclick=updateTotals() type=checkbox value=true>
<SCRIPT>
document.write(TaxableState)
</SCRIPT>
</P></TD>
<TD width=120>
<CENTER>
<P>IVA:</P></CENTER></TD>
<TD width=120>
<CENTER>
<P><INPUT maxLength=10 name=salestax onfocus=this.blur()
size=10></P></CENTER></TD></TR>
<TR>
<TD width=264>
<TD width=120>
<CENTER>
<P>Total: </P></CENTER></TD>
<TD width=120>
<CENTER>
<P><INPUT maxLength=10 name=grandtotal onfocus=this.blur()
size=10></P></CENTER></TD></TR></TBODY></TABLE>
<!--<P><B>Bill To:</B> <! Onto Bill To and Ship To address portions of the form></P>
<TABLE align=center border=1>
<TBODY>
<TR>
<TD width=120>
<P>Name:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billName size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Company:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billCompany size=50> </P></TD></TR>
<TR>
<TD width=120>
<P>Address1:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billAdd1 size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Address2:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billAdd2 size=50> </P></TD></TR>
<TR>
<TD width=120>
<P>City, State, Zip:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billCSZ size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Phone:</P></TD>
<TD width=408>
<P><INPUT maxLength=25 name=Phone size=25></P></TD></TR>
<TR>
<TD width=120>
<P>Email address:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=email size=40></P></TD></TR></TBODY></TABLE>
<CENTER>
<P><INPUT onclick=copyAddress() type=button value="Copy 'Bill To' info to 'Ship To' blanks">
</P></CENTER>
<P><B>Ship To:</B> </P>
<TABLE align=center border=1>
<TBODY>
<TR>
<TD width=120>
<P>Name:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipName size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Company:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipCompany size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Address1:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipAdd1 size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Address2:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipAdd2 size=50></P></TD></TR>
<TR>
<TD width=120>
<P>City, State, Zip:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipCSZ size=50></P></TD></TR></TBODY></TABLE>
<P><! In real life, you'd want to omit the whole onclick... thing in the input tag below. ><! Which is to say you want to get rid of... ><! onClick = "alert('I do not really get submitted anywhere. But thanks for trying me!')" ><INPUT onclick="alert('I do not really get submitted anywhere. But thanks for trying me!')" type=submit value=Submit>
<INPUT type=reset value=Reset> <! In real life, you can omit the entire input tag (i.e. the entire line) below ><INPUT onclick="self.location = 'jsindex.htm'" type=button value="All Done">
</FORM></P>-->
</body>
</html>

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('');

Categories