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

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)

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.

Calculate quantity and total on an order form in 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>

I'm trying to get the innerHTML function in Javascript to work

I want the heating answer to appear next to the Heating Surface (mm) but I can't make it work. I only get the following error message from the chrome console
Uncaught TypeError: Cannot read property 'value' of null
I know everything else works because I added an alert box, I need the innerHTML to work though.
Here is the html:
<html>
<head>
<script type="text/javascript" src="pipeheaterfunction.js">
</script>
</head>
<body>
<table>
<tr><td>Inner Diameter (mm):</td>
<td><input id="dia" onkeypress="pipeheater();"></td>
<tr><td>Pipe Thickness (mm):</td>
<td><input id="thi" onkeypress="pipeheater();"></td>
<tr><th>Calculate heater:</th>
<td><button onclick="pipeheater();">Calculate</button></td></tr>
<tr><td>Heating Surface(mm):</td>
<td><span class="output" id="surface"></span></td></tr>
</table>
</body>
</html>
Here is the javascript code:
function pipeheater(){ //dia is the inner diameter of a pipe, thi is the pipe thickness
var dia = document.getElementById("dia").value;
var thi = document.getElementById("thi").value;
var hsur; //hsur is the heating surface required for a certain pipe in mm
hsur = 5*Math.sqrt(((dia-thi)*thi)/2);
var surface = hsur;
if(surface>0){
surface.innerHTML=surface.toFixed(1);
alert(surface.toFixed(1));
}
}
window.onload=pipeheater();
There are two errors in your script. At first, when setting
window.onload = pipeheater();
pipeheater is invoked immediately, it's not waiting window.onload to be fired, and you get an error when trying to read a value of yet-non-existing element. You can fix this like this:
window.onload = pipeheater;
Secondly, you try to use innerHTML of hsur, which is a number. You need to define a variable for the actual HTML element. Below is your fixed code.
function pipeheater() {
var dia = document.getElementById("dia").value,
thi = document.getElementById("thi").value,
hsur = 5 * Math.sqrt(((dia - thi) * thi) / 2),
surface = document.getElementById("surface");
if (hsur > 0) {
surface.innerHTML = hsur.toFixed(1);
alert(hsur.toFixed(1));
}
}
window.onload = pipeheater;
You can check how this works at jsFiddle. I'd recommend you to validate values of dia and thi before making any calculations with them. Also using onchange instead of onkeypress might be more comfortable for users, and would give you more reliable results.
You forgot to define "surface".
var surfaceSPAN = document.getElementById("surface");
You can then do:
surfaceSPAN.innerHTML = surface.toFixed(1);
Do note that you cannot use the variable name "surface" twice in one script, as they would overrule eachother and you'd have no variable result.

change value when checked [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 9 years ago.
I am new into HTML DOM . I am trying to change value when check-box checked.
So here is my unfinished script:
<html>
<script type="text/javascript">
var val=12;
document.write("<p>"+val+"</p>");
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
var val=val+2;
}
}
function checkAddress2()
{
var chkBox = document.getElementById('checkAddress2');
if (chkBox.checked)
{
var val=val+3;
}
}
function checkAddress3()
{
var chkBox = document.getElementById('checkAddress3');
if (chkBox.checked)
{
var val=val+4;
}
}
</script>
<p>Get value :<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()" value="1st"/>
Get value :<input type="checkbox" id="checkAddress2" name="checkAddress" onclick="checkAddress2()" value="2nd"/>
Get value :<input type="checkbox" id="checkAddress3" name="checkAddress" onclick="checkAddress3()" value="3rd"/>
Here, i just want to make this script: when checkbox click it will change the value auto.
First off your declaring val within the {} each time which means the value is lost.
Secondly, you don't do anything with val in order for it to be useful.
Finally, you could have one function instead of three where you pass the specific checkbox that was clicked.
Additionally,as stated in the comments you do not assign val to any elements (using .innerHtml, textarea, etc). Which means value is not seen.
<html>
<script type="text/javascript">
var val=12;
function resetCheckboxes()
{
document.getElementById("checkAddress").checked=false;
document.getElementById("checkAddress2").checked=false;
document.getElementById("checkAddress3").checked=false;
}
function checkAddress(chkBox)
{
var multiplyer = 1;
if (!chkBox.checked)
multiplyer = -1;
if(chkBox.id =="checkAddress")
val=val+ (multiplyer)*2;
else if(chkBox.id =="checkAddress2")
val=val+ (multiplyer)*3;
else if(chkBox.id =="checkAddress3")
val=val+ (multiplyer)*4;
document.getElementById("displayValue").innerHTML = "Val:"+val;
}
</script>
<body onLoad="resetCheckboxes()">
<div id="displayValue">Val:12</div>
<p>Get value :<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress(this)" value="1st"/>
Get value :<input type="checkbox" id="checkAddress2" name="checkAddress" onclick="checkAddress(this)" value="2nd"/>
Get value :<input type="checkbox" id="checkAddress3" name="checkAddress" onclick="checkAddress(this)" value="3rd"/>
</body>
</html>

JavaScript Real Time Calculation

I have built a table with custom inputs numbers with jeditable. The Input type is gone once you put the value
I need to find a JavaScript Real Time Calculation which automatically makes the amount of my values.
I have found 2 interesting examples very suitable for my case but there is the possibility to achieve it the same without using the form and inputs?
First example
Second example
Yes, it is. As you know a div element can be accessed by document.getElementById('div_id') and its value can be accessed by document.getElementById('div_id').value.
So take out the form and insert an id for the div's that you need and access the value and then find the sum and then set the value as the sum to another div. Here is the code
<script>
function calculateBMI() {
var wtStr =document.getElementById('w').value;
if (!wtStr)
wtStr = '0';
var htStr = document.getElementById('h').value;
if (!htStr)
htStr = '0';
var weight = parseFloat(wtStr);
var height = parseFloat(htStr);
document.getElementById("r").value = weight + height;
}
</script>
<input id = "w" type="Text" name="weight" size="4" onkeyup="calculateBMI()"> Weight (in Kilos)
<input id = "h" type="Text" name="height" size="4" onkeyup="calculateBMI()"> Height (in Centimeters)<br>
<input id = "r" type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
<input type="button" style="font-size: 8pt" value="Calculate" onClick="calculateBMI()" name="button">
​and if you don't want input you can use textarea.

Categories

Resources