Calculate quantity and total on an order form in javascript - javascript

I'm looking for some help with a bit of code please. I'm supposed to create a form that allows the user to input a quantity for items which they wish to purchase. When the quantity is input, the total price for that particular item is displayed, and the grand total (at the bottom of the form) for all purchases.
When the user presses the submit button, an alert popup appears.
I'm having trouble with the calculation part in javascript. It is not calculating any of the total amount or quantity values.
(For some reason the code won't indent here properly but they are in the actual documents).
function calc(){
var QtyA = 0; var QtyB = 0; var QtyC = 0;
var TotA = 0; var TotB = 0; var TotC = 0;
var PrcA = 3; var PrcB = 4; var PrcC = 5.50;
if (document.getElementById('QtyA').value > "");{
QtyA = document.getElementById('QtyA').value;}
TotA = eval(QtyA) * eval(PrcA);
TotA = TotA.toFixed(2);
(document.getElementById('TotalA').value = TotA);
if (document.getElementById('QtyB').value > "");{
QtyB = document.getElementById('QtyB')value;}
TotB = eval(QtyB) * eval(PrcB);
TotB = TotB.toFixed(2);
(document.getElementById('TotalB').value = TotB);
if (document.getElementById('QtyC').value > "");{
QtyC = document.getElementById('QtyC')value;}
TotC = eval(QtyC) * eval(PrcC);
TotC = TotC.toFixed(2);
(document.getElementById('TotalC')value = TotC);
Totamt = eval(TotA) + eval(TotB) + eval(TotC);
Totamt = Totamt.toFixed(2); //fix to 2 decimal places
(document.getElementById('Grand Total is: ').value = Totamt);
alert (Totamt);
<html>
<head>
<meta charset="UTF-8">
<title>Order Form</title>
<style>
#import "css/OrderForm.css";
</style>
<body>
<form>
<table border="1">
<tr>
<th>Item</th>
<th>Image</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td width="80">Hat</td>
<td><img src="images/hat.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA" size="5" onchange "calc()"></td>
<td>€3.00</td>
<td>
<input type="text" id="TotalA" size="12" onchange "calc()">
</td>
</tr>
<tr>
<td width="80">T Shirt</td>
<td><img src="images/t_shirt.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA" size="5" onchange "calc()"></td>
<td>€4.00</td>
<td>
<input type="text" id="TotalA" size="12" onchange "calc()">
</td>
</tr>
<tr>
<td width="80">Glasses</td>
<td><img src="images/glasses.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA" size="5" onchange "calc()"></td>
<td>€5.50</td>
<td>
<input type="text" id="TotalA" size="12" onchange "calc()">
</td>
</tr>
<tr>
<td> Total: </td>
<td><input type="text" id="GrandTotal" size="15" onchange="calc()"></td>
</tr>
</table>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>

Ok, as a teacher, I just can't let all the bad habits that someone is trying to teach you go. So, here we go....
eval() is EVIL - Don't use it, ever!
eval() tells the JavaScript runtime to process a string as if it were JavaScript. This is very dangerous because if the string contains malicious code, eval() will run it. In your code, you run eval() on the value entered into a text box and since you have no idea what value will be entered, you also have no idea what string eval() will receive. This equates to a huge security hole and is one of the reasons eval() should not be used. Secondly, even in a perfect world, eval() is slow, so from a purely performance standpoint, you wouldn't want to use it. Frankly, I'm shocked that someone taught you to use it and especially for converting strings to numbers. That alone is enough to ask for your money back!
In your case, you need to convert the string input into numbers so that you can do math with the input. JavaScript offers several ways to do this:
parseInt(stringContainingNumber, radix)
parseFloat(stringContainingNumber)
Number(stringContainingNumber)
+stringThatIsNumber Unary Operator
Don't set up your event handling in HTML with event attributes.
When JavaScript was first created (25+ years ago), the way to set up an event handler for an HTML element (a.k.a DOM element) was to use HTML attributes such as onclick, onchange, onmouseover, etc. inline with the element in the HTML. Unfortunately, because of how simple that technique looks it gets used over and over again instead of dying the quick death it deserves. There are several reasons not to use this outdated technique. Today, we have modern standards and best practices to follow and so, event handling should be done in JavaScript, separate from HTML, with .addEventListener()
Also, your code of: onchange "calc()" was incorrect anyway because the code should have been: onchange = "calc()".
Additionally, think about what elements need events set up for them. Your original code had it set up so that if the total gets changed, calc() would run, but that makes no sense. Why would someone be able to change the total directly and what would doing so actually cause to happen? Should the quantity change because the total has changed?
Pay attention to details
You have 3 rows to calculate 3 quantities * 3 prices to get 3 totals, but you just copied/pasted the HTML for the 3 rows and wound up with 3 input elements with the same id of QtyA even though your JavaScript was correctly looking for QtyB and QtyC.
Do your styling with CSS, not HTML
All of your quantity input fields need to have their width set to a size of 5. Don't use the HTML size attribute for that, do it with the width CSS property. The HTML will be cleaner and you won't have to repeat the same instruction 3 times.
#import is being used incorrectly
The CSS #import directive is meant to be used as the first line in external stylesheets that import instructions from another stylesheet, effectively combining multiple sheets into one. If you have only one stylesheet to use, you don't import it, you link to it.
Instead of: <style> #import "css/OrderForm.css";</style>
use: <link href="css/OrderForm.css" rel="stylesheet">
When you are just displaying a result, don't place it into a form field.
There's no reason to put a total into an input field when you don't want the user to be able to modify that result. Instead, just place it as the text of a non-editable element - - in your case the appropriate cell of the table.
Lastly: Use the developer's tools!
All modern browsers incorporate "developer's tools", which you can activate by pressing F12. There are many tabs in the tools, but the "Console" tab is probably the most important for you right now. If you have errors in your syntax (as you did), the Console will show them and the line number. You must eliminate all of your syntax errors before you can expect your code to run.
The Console is also an invaluable tool for testing values in your code. You can insert:
console.log(anything that is supposed to produce a value);
into your code to verify that variables, elements, etc. have the values you think they do.
Now, in reality, I would go about solving this problem in a very different way that you are attempting, but that is more complex than you are ready for at this stage, so I've gone along with your approach somewhat.
Please read through the HTML and JavaScript comments carefully to explain what's being done.
<!DOCTYPE html> <!-- The DOCTYPE tells the browser what version of HTML it should be expecting. -->
<html>
<head>
<meta charset="UTF-8">
<title>Order Form</title>
<!-- To reference a single stylesheet, use the link element: -->
<link href="css/OrderForm.css" rel="stylesheet">
<style>
/* Make all the input elements that have an id that starts with Qty
be 5 characters wide. (Now size=5 isn't needed in the HTML 3 times) */
input[id^=Qty] { width:5em; }
/* The first <td> in each row should be 80px wide. Now we don't have to
clutter up the HTML with this and we don't have to repeat it 3 times. */
td:first-child { width:80px; }
</style>
</head> <!-- You didn't close your <head> tag! -->
<body>
<form>
<table border="1">
<tr>
<th>Item</th>
<th>Image</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td>Hat</td>
<td><img src="images/hat.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA"></td>
<td>€3.00</td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<td id="TotalA"></td>
</tr>
<tr>
<td>T Shirt</td>
<td><img src="images/t_shirt.jpg" alt="T-Shirt"></td>
<td><input type="text" id="QtyB"></td>
<td>€4.00</td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<td id="TotalB"></td>
</tr>
<tr>
<td>Glasses</td>
<td><img src="images/glasses.jpg" alt="Glasses"></td>
<td><input type="text" id="QtyC"></td>
<td>€5.50</td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<td id="TotalC"></td>
</tr>
<tr>
<td> Total: </td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<!-- You need to have this cell span over the remaining columns of the
table, so colspan=4 needs to be added. -->
<td id="grandTotal" colspan="4"></td>
</tr>
</table>
<!-- Your form doesn't actually submit data anywhere, so you shouldn't
have a submit button. A regular button will do. -->
<input type="button" value="Get Grand Total">
<input type="reset" value="Reset">
</form>
<script>
// Get references to the HTML elements that you'll be working with
var qtyBoxA = document.getElementById('QtyA');
var qtyBoxB = document.getElementById('QtyB');
var qtyBoxC = document.getElementById('QtyC');
var totBoxA = document.getElementById('TotalA');
var totBoxB = document.getElementById('TotalB');
var totBoxC = document.getElementById('TotalC');
var grandTot = document.getElementById('grandTotal');
var btnGetTot = document.querySelector("input[type=button]");
var btnReset = document.querySelector("input[type=reset]");
// Set up event handling in JavaScript, not HTML.
qtyBoxA.addEventListener("change", calc);
qtyBoxB.addEventListener("change", calc);
qtyBoxC.addEventListener("change", calc);
btnGetTot.addEventListener("click", getGrandTotal);
btnReset.addEventListener("click", reset);
var gt = null; // Will hold the grand total
function calc() {
var priceA = 3;
var priceB = 4;
var priceC = 5.50;
gt = 0;
// Convert the values in the quantity textboxes to numbers. The 10 that
// is being passed as the second argument indicates the "radix" or the
// numeric base system that should be used when the string is being
// interpreted. Here (and often), we work in the base 10 numeral system.
var qtyA = parseInt(qtyBoxA.value, 10);
var qtyB = parseInt(qtyBoxB.value, 10);
var qtyC = parseInt(qtyBoxC.value, 10);
// If each of the quantity fields are not empty, calculate the price * quantity
// for that row, place the answer in that row's total field and add the answer
// to the grand total
// NOTE: You had semicolons like this: if(); {}, which is incorrect.
// NOTE: Notice that there are + signs right in front of the total box references?
// this forces a conversion of the string in the text to a number. Since we
// just put a number into the cell, we know for sure it can be converted.
// NOTE: If parseInt() can't parse a number from the string provided, it returns NaN
// (Not A Number), we can check to see if we got NaN with the isNaN() function
// and here, we want to know if we don't have a NaN, so we prepend a ! to it
// (the logical NOT operator) to test the opposite of the isNaN() function result.
if (!isNaN(qtyA)) { totBoxA.textContent = qtyA * priceA; gt += +totBoxA.textContent; }
if (!isNaN(qtyB)) { totBoxB.textContent = qtyB * priceB; gt += +totBoxB.textContent; }
if (!isNaN(qtyC)) { totBoxC.textContent = qtyC * priceC; gt += +totBoxC.textContent; }
grandTot.textContent = gt.toFixed(2); // Just place the answer in an element as its text
}
function getGrandTotal(){
calc(); // Make sure all values are up to date
alert(gt);
}
function reset(){
// The built-in functionality of the <input type=reset> will clear out
// the quantity input fields automatically, but we need to manually reset
// non form field element that have been modified:
totBoxA.textContent = "";
totBoxB.textContent = "";
totBoxC.textContent = "";
grandTot.textContent = "";
}
</script>
</body>
</html>

Related

Sum a calculated <td> value

I am creating a calculator that converts a different opioids medications to a standard opioid dosage. The calculator converts all medications fine but I cannot get the javaScript sum() function to add it all up when a button is clicked. Please help.
Of note, the "totalMED += total[i]).value;" code inside the for loop breaks the medication calculate function (no value is displayed). I don't know why.
P.S. I realize both calculate() functions are basically the same but I couldn't get the relevant values to loop through a single function. I seem to have problems with loops.
Updated code with comments:
<!DOCTYPE html>
<html>
<head>
<SCRIPT language="javascript" src="date.js"></SCRIPT>
<style type="text/css">
...
</style>
</head>
<body>
<form>
<table>
<tr>
<th>Medications</th>
<th>Daily Dose (mg)</th>
<th>MED</th>
<th>Medications</th>
<th>Daily Dose (mg)</th>
<th>MED</th>
</tr>
<tr>
// ---this input box is really just a label----
<td><input class="tg-yw41" type=”text” name=”Tramadol” value=Tramadol id="med”
disabled></td>
// ----This input box takes user entered dosage, calls calculate() function, and
// passes the conversion factor---
<td>'TEXT"</td><td><input class ="tg-yw41" type=”text” name=”dose” value=""
placeholder="0" Id="r18c2" onchange="calculate28('.1')"></td>
//---This input box receives the value from the calculate function via Id="MED-
// Tramadol". Also includes name="sum" for sum() function.
<td><input Id="MED-Tramadol" type=”text” name="sum" value="" disabled></td>
//----The next three rows are just duplicate of above
<td><input class="tg-yw41" type=”text” name=”Sufentanil” value="Sufentanil"
disabled></td>
<td><input class ="tg-yw41" type=”text” name=”dose” value="" placeholder="0"
Id="r18c5" onchange="calculate29('60')"></td>
<td><input Id="MED-Sufentanil-intra" type=”text” name="sum" value="" disabled></td>
</tr>
<tr>
//-----Label
<td><input value="Total Daily Morphine Equivalent Dose (MED) in Milligrams"
disabled></td>
//---Input box that should receive value from sum() function (via ID="r19c2")
<td><input class ="tg-yw41" type=”text” name=”dose” value="" placeholder="0"
Id="r19c2"></td>
</tr>
//A button that when clicked calls the sum() function
</table>
<button type="button" onclick="sum()">MED total</button>
JavaScript functions
<script type="text/javascript">
//Takes user input * passed conversion factor, assigns value to
document.getElementById('MED-Tramadol')
function calculate28(x)
{
var my1 = x;
var my2 = document.getElementById('r18c2').value;
//Note: value is parsed as a Float...don't know if it gets converted back to string
document.getElementById('MED-Tramadol').value = parseFloat(my1) * parseFloat(my2);
}
//same as above
function calculate29(x)
{
var my1 = x;
var my2 = document.getElementById('r18c5').value;
document.getElementById('MED-Sufentanil-intra').value = parseFloat(my1) * parseFloat(my2);
}
//Supposed to combine all values from calculate() function assigned to respective boxes
function sum() {
//should collect value from all <input> with name="sum"
var total = document.getElementsByName('sum').value;
var sum = 0;
for(var i=0; i<total.length; i++)
{
totalMED += paredFloat(total[i]).value);
}
document.getElementById('r19c2').value = totalMED;
When you pull the value of an input box, it's read as a string. Use parseInt() to get the number, otherwise you're concatenating strings.
Since you're taking in user input, you should also validate it. A simple way to make sure you don't get NaN is to pull the value into a temporary variable and test it before parsing.
var strTemp = total[i].value;
if (strTemp)
{
totalMED += parseInt(test);
}
EDIT: I ignored the paren, thinking it was just a typo in the question. I decided I shouldn't. You'll see small errors like the unmatched ) inside your call easily if you check your browser's JS console, as this would certainly halt the program and provide an error message.
I'm just going to post this answer out here, and if it doesn't help or it's close then we can edit as we see fit.
First of all, are you sure that you are receiving the correct values in each of the variables? For example, var total = document.getElementsByName('sum').value; should return as undefined.
Secondly, totalMED += total[i]).value; is not valid Javascript, and even if var total = document.getElementsByName('sum').value; were to give you an array of actual values.. then totalMED += total[i]).value; would just concatenate strings. For example, if you have 2 input elements on your page, and the first has a value of 20 and the second has a value of 25 then, your output would be 02025, because value is of type string.
I think this may help:
Javascript
function sum()
{
var total = document.getElementsByName('sum');
var totalMED = 0;
for(var i = 0; i < total.length; i++)
{
if(!isNaN(parseInt(total[i].value)))
{
console.log(total[i].value);
totalMED += parseInt(total[i].value);
}
}
console.log(totalMED);
}
Here is a JSFiddle to prove that it's working.
Let me know if this helps.

Using the current variable when tracking multiple variables with jQuery event

Below you'll find a simplified example of the code I am using and what I am trying to accomplish.
I'm tracking multiple variables with jQuery that need to call a function on a certain event. The problem is that I don't manage to use only that variable that just changed.
In the HTML body section I have a couple of input fields where people can fill in a number. That number should be formatted with commas as a thousand seperator. Thanks to Elias Zamaria I found an good solution for this (https://stackoverflow.com/a/2901298/7327579). Now I want this implemented with jQuery so I can track all of my variables that will get number inputs at once.
<html>
<title></title>
<head>
In the head of the html I insert my script to track my variables:
<script language="javascript">
var Currency = function() {
this.currencyType = $("#businessAuthorisation, #businessIncome, #entityIncome, #entityAuthorisation);
The function that formats the numbers and should only get the current number from the current variable that is being changed:
this.formatCurrency = function(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
};
};
Tracking starts and on the keyUp event my function is called. Only the current variable should be a parameter of the called function.
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
currency.formatCurrency(this);
});
});
</script>
</head>
Here below are the concerning input fields in my form:
<body>
<form>
<table>
<tr>
<td><input type="number" name="entityAuthorisation" id="entityAuthorisation" value="<%=entityAuthorisation%>></td>
</tr>
<tr>
<td><input type="number" name="businessAuthorisation" id="businessAuthorisation" value="<%=businessAuthorisation%>"></td>
</tr>
<tr>
<td><input type="number" name="entityIncome" id="entityIncome" value="<%=entityIncome%>"></td>
</tr>
<tr>
<td><input type="number" name="businessIncome" id="businessIncome" value="<%=businessIncome%>"></td>
</tr>
</table>
</form>
</body>
</html>
How can I make sure that that the function only applies to the current element that caused the event?
In a jQuery event handler, this refers to the element that the event was triggered on. And you need to use .value to get the value of an input. So you should write:
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
this.value = currency.formatCurrency(this.value);
});
});

how to use split() function in classic ASP for mass inputs textbox?

I am trying to use the split function in classic ASP using JavaScript. I need to have a big text box where I can keep group of bar-code numbers of products. Once submit button is clicked These bar-code numbers needed to be split by each and every character term for all bar-code numbers (in a loop). For instance, if i have 5 bar-code numbers, I have to split first bar-code number by each and every character/number, keep into array and continue same process to all 5 bar-code numbers. I wanted to display the result of split-ted numbers into a paragraph for myself just to check if its working. Below is the code I was working on. It doesn't show me anything when i click the button. I am not being able to figure out my logical error or what am I missing. How do I fix it? I didn't find any helpful solution when i was doing research.
<p id="demo"></p>
<form name="submitticket" action="<%=Request("script_name")%>" method="post">
<input type="hidden" name="action" value="sendform">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td align="center" colspan="2">
<br /><textarea name="noskews" id="skewsip" rows="50" cols="100" wrap="soft" maxlength="5000"><%=Request("noskews")%></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="padding-top:20px;">
<input type="submit" name="clearNoskew" value="Submit" class="a-t-button-mini">
</td>
</tr>
</table>
</form>
<script>
$("form").on("click", ".a-t-button-mini", function(event){
//var clickedId = $(this).attr('value')+','; // give me first numbers,
var locationBtn = $('#skewsip'); // Select the input
var locationBtnValue = $('#skewsip').val(); // Take the select value
var ids = locationBtnValue.split(',');
document.getElementById("demo").innerHTML = ids; //want to display in a paragraph for myself
});
</script>
I was able to split one barcode (out of total 5 barcodes entered inside textarea) by every characters and display it into div. for example: I entered 5465 8989 7586 5236 5486 (These barcodes are entered using "enter or new line" after every 4 numbers; space in above example means the next barcode is in next line). I get split output of (5,4,6,5) which I need but it didn't give me for rest of my barcodes. In other words, I couldn't do same for all 5 total bar codes entered into the textarea/textbox. I know its only "for loop" When I kept for loop in my code, it executes for first barcode out of 5 barcodes.
<script>
$("#form").on("click",".a-t-button-mini", function(event){
var locationBtnValue = $('#skewsip').val();
var skews_array = locationBtnValue.split("",12);
// for (i = 0; i < locationBtnValue.length; i++) {
// text += skews_array[i] + "<br>";
document.getElementById("test").innerHTML = skews_array;
// }
});
</script>
I think you're saying each barcode on a new line of the textarea. If so, this should work for you (\n is the newline character), at least to capture and re-output to the demo element:
<script>
$("form").on("click", ".a-t-button-mini", function(event){
var ids = $("#noskews").val().split('\n');
$.each( ids, function( index, value ) {
$("#demo").append(index + ' - ' + value + '<br/>');
});
});
</script>
Added working code to codepen:
http://codepen.io/anon/pen/NxENYW

Using array elements to assign “id=” values returns: TypeError: document.getElementById(...) is null

I'm trying to write calculated values to table cells referencing them by their id= tag that are chosen using array elements. All attempts to get this working such as where “ “ are coded, and first trying spans[index]= spans[index].toString(); and using window.setTimeout(function () { code.. }, 0); gives the above error.
The many of the similar questions that I have found posted have responses suggesting that the error is related to page loading.
I am either misunderstanding the solutions given or what I'm attempting is different. It would be appreciated if someone could give an example of how this is accomplished.
function outputResults() {
var spans = ['span1', 'span2', 'span3'];
var outputs = ['output1', 'output2', 'output3'];
for (var index = 0; index < spans.length; index++)
{
outputs[index] = (outputs[index] * 13) / 100;
(document.getElementById('\'spans[index]\'').innerHtml = outputs[index]);
};
};
<table BORDER="1" width="300" />
<tr />
<td /> <span id="span1"> </span> </td>
<td /> <span id="span2"> </span> </td>
<td /> <span id="span3"> </span> </td>
</tr>
</table>
<br />
<input type="button" value="Click to fill cells" onclick="outputResults();" />
First, let's look at this line:
outputs[index] = (outputs[index] * 13) / 100;
What do you expect to happend here? Say index equals 0. outputs[0] == 'output1'. Your assignment is doing this (meta):
outputs[0] = ('output1' * 13) / 100;
You should revise this statement. As to your error, this should work for you:
document.getElementById(spans[index]).innerHtml = outputs[index];
EDIT:
There are a lot of problems with your code. You need to fix your HTML (self-closed td and tr tags) and your JavaScript code (outputs values and innerHTML). Please see working example here: http://jsfiddle.net/pkRmC/2/
Use document.getElementById(spans[index]) if you don't want to select the (nonexisting) element with the literal id "'spans[index]'".
Btw, all your opening tags do incorrectly end with />, while it should be just >. Not sure how you did not get a big HTML parse error from that. The /> syntax is only permitted for self-closing elements such as hr, br, meta etc, and actually is only necessary in XHTML.
Also, your computation of outputs[index] * 13) / 100 does not make too much sense, since you are multiplying a string with the number 13 - which will result in NaN. Not sure what you wanted to achieve with that.

BMI Calculator... except BMI won't show up [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Good evening, everyone :>
I am currently trying to finalize code for a simple BMI calculator. The trouble is that it won't show me a BMI reading when I input my height and weight in my browser. I'm 99% certain that my HTML is solid, it's just the Javascript that seems to be causing problems. Any input I can get on this matter would be appreciated. Thanks!
<!DOCTYPE HTML>
<html>
<head>
<title>BMI Calculator</title>
<script type="text/javascript">
/* <![CDATA[ */
function calculate() {
var height = document.getElementById("height");
var weight = document.getElementById("weight") * 703;
var denom = Math.pow(height, 2);
var totalbmi = weight/denom;
var bmi = document.getElementById("bmi");
if (isFinite(bmi)) {
bmi.innerHTML = totalbmi.toFixed(2);
}
}
/* ]]> */
</script>
<style type="text/css">
<!--
.result {font-weight: bold; }
-->
</style>
</head>
<body>
<form name="details">
<table>
<tr>
<td>Height<br />
(in Inches)</td>
<td><input type="text" size="3" id="height" onChange="calculate();"/></td>
</tr>
<tr>
<td>Weight<br />
(in Pounds)</td>
<td><input type="text" size="3" id="weight" onChange="calculate();"/></td>
</tr>
<tr>
<td><input type="button" value="My BMI" onClick="calculate();"/></td>
</tr>
</table>
</table>
<table width="270">
<tr>
<td width="104">Your BMI is:</td>
<td width="154"><input type="text" id="totalbmi"></span></td>
</tr>
</table>
</form>
</body>
</html>
It's not going to update anything because you have var bmi = document.getElementById("bmi");
when it should be var bmi = document.getElementById("totalbmi");
document.getElementById() returns the HTML node, not the text inside it. To get the actual weight and height values provided by the user, you should use document.getElementById("height").value.
As nathanjosiah pointed out as well, you're referring to a "bmi" node where you probably meant "totalbmi". You're also confusing your 'bmi' and 'totalbmi' variables.
function calculate() {
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value * 703;
var denom = Math.pow(height, 2);
var totalbmi = weight/denom;
var bmi = document.getElementById("totalbmi");
if (isFinite(totalbmi)) {
bmi.value = totalbmi.toFixed(2);
}
}
EDIT: As others pointed out, you want to set the .value of an input in order to change its displayed content. <input> elements are empty, so setting one's .innerHTML property doesn't work.
document.getElementById() returns a reference to the (matching) DOM element itself, not to its value. To get/set the value use the .value property.
Also you are trying to set the result to a field with id "bmi" when the actual field has the id "totalbmi", and you are trying to set that field's .innerHTML (which input elements don't have) instead of its .value.
So taking those problems into account:
function calculate() {
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value * 703;
var denom = Math.pow(height, 2);
var totalbmi = weight/denom;
document.getElementById("totalbmi").value =
isFinite(totalbmi) ? totalbmi.toFixed(2) : "";
}
(Where if the results fail the isFinite test I'm setting the output field to an empty string rather than leaving whatever value was in it before.)
In the following line you id is totalbmi, but you are using document.getElementById("bmi");
<input type="text" id="totalbmi">
Also, to set the value of the input you would do
bmi.value = totalbmi.toFixed(2)
instead of
bmi.innerHTML = totalbmi.toFixed(2)

Categories

Resources