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.
Related
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.
Afer going through all the suggestions, this is what i have come with. But if I am having something like $100 instead of 100, is there anyway i can covert it into number ?
var selectedRows = document.getElementsByClassName('selected');
limit = 0; //set limit
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]');
function checker(elem) {
if (elem.checked) {
limit++;
} else {
limit--;
}
for (i = 0; i < checkboxes.length; i++) {
if (limit == 2) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true;
}
} else {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false;
}
}
}
}
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function() {
checker(this);
}
}
function inputChanged(event) {
event.target.parentElement.parentElement.className =
event.target.checked ? 'selected' : '';
}
function Calculate() {
var cal = 0;
for (var i = 0; i < selectedRows.length-1; i++) {
cal = Number(selectedRows[i].textContent - selectedRows[i+1].textContent);
}
alert(Number(cal))
}
background-color: yellow;
<table class="checkboxdiv">
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>$100</td>
</tr>
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>$20</td>
</tr>
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>$40</td>
</tr>
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>$21</td>
</tr>
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>$12</td>
</tr>
</table>
<button onclick="Calculate()">Calculate</button>
Hi I am trying to calculate the difference between two values of the checkbox and displaying the popup (alert box). I am getting 2 issues here
After getting the result popup I am getting one more pop up which says Nan. How do i remove that?
I want to limit the number of selected checkbox to 2, once 2 checkboxes are selected remaining should be disabled I have written the code to if length is greater than 2, checkbox should be disabled but that is not working.
var selectedRows = document.getElementsByClassName('selected');
if(selectedRows.length>2){
document.getElementById("mycheck").disabled = true;
}
function inputChanged(event) {
event.target.parentElement.parentElement.className =
event.target.checked ? 'selected' : '';
}
function Calculate() {
for (var i = 0; i < selectedRows.length; ++i) {
alert(selectedRows[i]?.textContent.trim() - selectedRows[i+1]?.textContent.trim());
}
}
.selected {
background-color: yellow;
}
<table>
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>100</td>
</tr>
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>20</td>
</tr>
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>40</td>
</tr>
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>21</td>
</tr>
<tr>
<td>
<input id = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>12</td>
</tr>
</table>
<button onclick="Calculate()">Calculate</button>
First of all the attribute id should be unique in a document, you can use class instead.
You should access the selectedRows inside the function Calculate.
Since you want to limit the number of selected checkbox to 2 your condition should be .length > 1.
You can try the following way:
function inputChanged(event) {
//get all checked
var mycheck = document.querySelectorAll('.mycheck:checked');
//get all unchecked
var mycheckNot = document.querySelectorAll('.mycheck:not(:checked)');
if(mycheck.length > 1){
//disabled all unchecked
for (var i = 0; i < mycheckNot.length; i++) {
mycheckNot[i].disabled = true;
}
}
else{
//enable all unchecked
for (var i = 0; i < mycheckNot.length; i++) {
mycheckNot[i].disabled = false;
}
}
event.target.parentElement.parentElement.className =
event.target.checked ? 'selected' : '';
}
function Calculate() {
//get all selected
var selectedRows = document.getElementsByClassName('selected');
var sum = 0 ;
for (var i = 0; i < selectedRows.length; i++) {
//convert the value to number and sum them up
sum += Number(selectedRows[i].textContent)
}
alert(sum);
}
.selected {
background-color: yellow;
}
<table>
<tr>
<td>
<input class = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>100</td>
</tr>
<tr>
<td>
<input class = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>20</td>
</tr>
<tr>
<td>
<input class = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>40</td>
</tr>
<tr>
<td>
<input class = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>21</td>
</tr>
<tr>
<td>
<input class = "mycheck" type="checkbox" onchange="inputChanged(event)" />
</td>
<td>12</td>
</tr>
</table>
<button onclick="Calculate()">Calculate</button>
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 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>
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('');