Simple multiplication calculator not retaining decimal value - javascript

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>

Related

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

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

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.

Not getting the sum totals in Jquery/Javascript

Iam working on an application with certain calculations. I need to show and sum up the totals of Total INR and Margin Field. When a user put a percentage in Add (%) it calculates certain things and show the margin. And at the end script has to show the sum totals. Its showing Nan as of now.
My script is below:
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>//<![CDATA[
function isNum(value)
{
return 123;
}
function calcTotals1()
{
var grandTotal = 0;
var i = 0;
while (document.forms['cart'].elements['add_percentage[]'][i])
{
add_percentageObj = document.forms['cart'].elements['add_percentage[]'][i];
addon_valueObj = document.forms['cart'].elements['addon_value[]'][i];
total_inr_valueObj = document.forms['cart'].elements['total_inr[]'][i];
totalObj = document.forms['cart'].elements['add_value[]'][i];
marginObj = document.forms['cart'].elements['margin_for[]'][i];
if (isNaN(add_percentageObj.value)) {
add_percentageObj = '';
}
if (isNaN(addon_valueObj.value)) {
addon_valueObj = '';
}
if (add_percentageObj.value != 0) {
totalObj.value = (((total_inr_valueObj.value * 1) * add_percentageObj.value / 100) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total *1) + marginObj.value * 1);
} else if (addon_valueObj.value !=0) {
totalObj.value = ((addon_valueObj.value * 1) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total *1) + marginObj.value * 1);
} else {
totalObj.value = ((addon_valueObj.value * 1) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total *1) + marginObj.value * 1);
}
i++;
}
document.getElementById('grand_total').value = grandTotal.toFixed(3);
document.getElementById('margin_total').value = margin_total.toFixed(3);
//document.getElementById('total_inr1').value = total_inr1.toFixed(3);
//document.getElementById('margin_for').value = margin_for;
return;
}
</script>
</head>
<body>
<form name="cart" class="single">
<div align="center" class="base">
<table width="100%" border=1 style="border-collapse: collapse;">
<tr bgcolor="#E6E6FA">
<td colspan="6"><b>Terms and Cost</b></td>
</tr>
<tr>
<td>Terms</td>
<td>Total INR</td>
<td>Add (%)</td>
<td>Add Value</td>
<td>Total Value</td>
<td>Margin</td>
</tr>
<tr>
<td width="25%">Export Charges</td>
<td width="75%"><input type="text" id="total_inr[]" name="total_inr[]" value="13263.984"></td>
<td><input type="text" id="add_percentage[]" name="add_percentage[]" value="" onchange="calcTotals1()"></td>
<td><input type="text" id="addon_value[]" name="addon_value[]" value="" onchange="calcTotals1()"></td>
<td><input type="text" id="add_value[]" name="add_value[]" value=""></td>
<td><input type="text" id="margin_for[]" name="margin_for[]" value=""></td>
</tr>
<tr>
<td width="25%">IATA Charges</td>
<td width="75%"><input type="text" id="total_inr[]" name="total_inr[]" value="16579.98"></td>
<td><input type="text" id="add_percentage[]" name="add_percentage[]" value="" onchange="calcTotals1()"></td>
<td><input type="text" id="addon_value[]" name="addon_value[]" value="" onchange="calcTotals1()"></td>
<td><input type="text" id="add_value[]" name="add_value[]" value=""></td>
<td><input type="text" id="margin_for[]" name="margin_for[]" value=""></td>
</tr>
<tr>
<td></td>
<td><input name="gTotal" id="grand_total" style="font-weight: bold" size="20" /></td>
<td></td>
<td></td>
<td></td>
<td><input type='text' style='font-weight: bold' id='margin_total' name='margin_total' size='8' readonly /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
Try to use parseInt() to work really with integers instead of strings. If you read values from some html elements, you get these values as string. It also can cause wrong calculations. Just call parseInt() each time you read numeric value from html page element

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

Javascript Forms Calculator with No answers

I am very new to really writing javascript (borrowing and editing, not so new). So with a little help from google and code guru and adobe cookbook, I have come up with this simple form to be embedded into an iPad publication (this is just my test, not the final product). I have gotten it this far with no errors if the debug console and it seems to pass W3C compliance, but it also doesn't do anything! It doesn't generate the answers??? I am hoping someone can help me out or steer me in the right direction. the code for the page is below: Thanks in advance...
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.innerHTML = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.innerHTML = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.innerHTML = + (TotalsCost1 - TotalsCost2);
}
};
</script>
</body>
btn.onclick = (function(){...})();
You need to put onclick events inside self-calling code, or what are called closures. Move your entire btn.onclick function inside of this bit of code: (...)() in order to make it work.
Good attempt, a few small things wrong but pretty close!
I have made a few changes here.
As mentioned in a comment, I wrapped the function with brackets (function() {...});
I also changed innerHTML to be value as we are updating text inputs, and your savings calculation should be input.value, which I have updated for you.
Let me know how you get on!
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = (function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.value = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.value = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.value = + (TotalsCost1.value - TotalsCost2.value);
}
});
</script>
</body>

Categories