calculate bmi with javascript - javascript

I am currently creating a program that can calculate bmi with javascript. I am not sure why but it is not working properly. I must be missing something but I am not sure what it is. If someone could help me I would really appreciate it. Thank you.
<!DOCTYPE html>
<!-- -->
<html>
<head>
<meta charset="UTF-8" />
<title>Body Mass Index</title>
</head>
<BODY>
<header><img src="bmi.jpeg" width="380" height="132" border="0" alt="bmi"></header>
<video controls="controls"
width="320px" height="260px">
<source src="bmi.mp4"/>
<p>When it comes to weight loss, there's no lack of fad diets promising fast results. But such diets limit your nutritional intake, can be unhealthy, and tend to fail in the long run.</p>
<p>The key to achieving and maintaining a healthy weight isn't about short-term dietary changes. It's about a lifestyle that includes healthy eating, regular physical activity, and balancing the number of calories you consume with the number of calories your body uses.</p>
<p>BMI is a number calculated from a person's weight and height. BMI provides a reliable indicator of body fatness for most people and is used to screen for weight categories that may lead to health problems.</p>
<p>The BMI ranges are based on the relationship between body weight and disease and death.
Overweight and obese individuals are at increased risk for many diseases and health conditions, including the following:</p>
You need a flash player to view this video.
</video>
<ul>
<li>Hypertension</li>
<li>Dyslipidemia (for example, high LDL cholesterol, low HDL cholesterol, or high levels of triglycerides)</li>
<li>Type 2 diabetes</li>
<li>Coronary heart disease</li>
<li>Stroke</li>
<li>Gallbladder disease</li>
<li>Osteoarthritis</li>
<li>Sleep apnea and respiratory problems</li>
<li>Some cancers (endometrial, breast, and colon)</li>
</ul>
<script type="text/javascript">
function CalculateBMI(){
var inch=12;
var ft;
var bmi= Math.write(weight*703)/ (inch height)^2;
if(bmi<=19)
{"Underweight";
}
if else(19<bmi<=25)
{"Desirable";
}
if else(25<bmi<=29)
{"Prone to health risks";
}
if else (29<bmi<=40)
{"obese"
}
else(40<bmi)
{"Extremely Obese"
}
}
</script>
<form name="bmi">
<p> Weight:<p/></td> <td><input type="text" id="weight" name="weight" size="25" />
<p>Height:</p> <input type="text" id="textbox" name="textbox" size="25" /><td><p>Ft.</p><input type="text" id="textbox" name="textbox" size="25" /> <p>In.</p>
<input type="submit" id="Calculate BMI" name="Calculate BMI" value="Calculate BMI" size="25" onclick="CalculateBMI()" />
According to the Panel on
Energy, Obesity, and Body Weigth Standards published by
American Journal of Clinical Nurttrition, your category is:
<input type="text" id="textbox" name="textbox" size="25" />
</form>
</BODY>
</html>

I see a few things that are likely causing your issue. Lets start with this statement:
var bmi= Math.write(weight*703)/(inch height)^2;
You are not defining weight or height (you have to tell it to look in the textbox or send it to the function it does not automatically know you are referring to a textbox). I would expect something like
var weight = document.getElementById('weight').value;
There is no Symbol between height and weight, which is throwing a syntax error, you need to do something with these if they are going to be together (and do realize this is not adding the inches just calculating the feet in inches).
var bmi= (weight*703)/(inch*height)^2;
After that you are using if else - which is not valid in Javascript you would want to say:
else if (19<bmi<=25)
Lastly you are not returning a value nor specifying WHERE the value should go.
var results;
if (bmi<=19)
{
results = "Underweight"
}
document.getElementById('results').value = results;
Try implementing some of these suggestions and see if that gets you on the right track.

Your javascript had several systemic errors
for example 1<a<12 is not valid, it should be written a>1 && a<12
also, your CalculateBMI function had no idea what weight height in inches or height in feet where. You can include JQuery to make this easier but document.getElementById also works. To accomplish this I also gave meaningful names to your form variables.
You were not displaying the resulting string anywhere. Using getElementById you can also find the result element in your html and set its value to the result of the calculation.
If you don't want the page to refresh when you submit you have to set your form to receive a false value onsubmit.
Your math syntax for the bmi was off, I'm assuming it should be (703 * weight ) (height)^2 where height is in inches (after the foot and inch height variables have been combined).
The cleaned up Javascript should look like this. Note that this is probably not the best way to go about solving this problem.
edit: I think your BMI calculation was off as well. If the input weight and height are imperial (ie inch and lbs) then the inches should be multiplied by 0.025 to get meters and lbs should be multiplied by 0.45 to get kgs.
bmi= (weight_e* 0.45) / (((12*heightf_e)+heighti_e) * 0.025)^2;
function CalculateBMI(){
// To avoid erros due to hoisting define all
// of your vars at the top of your function
var ft,
bmi,
heighti_e, // height in inches
heightf_e, // height in feat
weight_e,
bmi_e, // the bmi element
bmi;
// Use getElementById to get a reference for the
// elements you will be using in your function
heighti_e=document.getElementById("heighti");
heightf_e=document.getElementById("heightf");
weight_e=document.getElementById("weight");
bmi_e=document.getElementById("bmi");
// Not all of these parenthesis are necessary but it
// helps to clear up the order of operation and avoid
// silly mistakes in long equations that are not
// broken up into several lines
bmi= (weight_e* 0.45) / (((12*heightf_e)+heighti_e) * 0.025)^2;
// set bmi to a string value
if(bmi<=19)
{
bmi="Underweight";
}
else if(bmi>19 && bmi<=25)
{
bmi="Desirable";
}
else if(bmi>25 && bmi<=29)
{
bmi="Prone to health risks";
}
else if (bmi>29 && bmi<=40)
{
bmi="obese";
}
else(bmi>40)
{
bmi="Extremely Obese";
}
bmi_e.value=bmi; // bmi_a is the reference to the
// element in your form with the
// bmi id
return false; // make sure you return false to prevent
// page reload
}
I have not cleaned up your HTML form, but at least it now works. I have moved the submission action from the button to the form tag. I have also given the height weight and bmi inputs meaningful id names so we can reference them in the CalculateBMI function.
<form action="" name="bmi" onsubmit="return CalculateBMI()">
<p> Weight:<p/></td> <td><input type="text" id="weight" name="weight" size="25" />
<p>Height:</p> <input type="text" id="heightf" name="textbox" size="25" /><td><p>Ft.</p><input type="text" id="heighti" name="textbox" size="25" /> <p>In.</p>
<input type="submit" id="Calculate BMI" name="Calculate BMI" value="Calculate BMI" size="25" />
According to the Panel on
Energy, Obesity, and Body Weigth Standards published by
American Journal of Clinical Nurttrition, your category is:
<input type="text" id="bmi" name="textbox" size="25" />
</form>

Related

I get NaN error when trying to create a basic calculator

I'm 3 days into learning Javascript and im really excited to understand more of this language, before i started i've done a basic HTML & CSS education. I'm currently on a 2 year program in a University in Sweden.
I'm trying to create a very basic calculator, that for now only adds 2 numbers together. I have 1 box, and another box. I want to make that each number written in each of these boxes is displayed as the total of box1, box2 in the third and final box.
At this moment i get "NaN" in the 3rd box when trying to add 2+3.
As i said, I'm really new and i appreciate all help i can get, and note that im not here for anyone to do my assignments which we have plenty of, i am really interessted in learning and understanding the language because i would like to work with this later in life when im done with my education.
Cheers!
<h1>Addera två tal med varandra</h1>
<form>
<input type="text" value="0" id="tal1" /> <br>
<input type="text" value="0" id="tal2" /> <br>
<input type="button" value="Beräkna" onClick="kalkylera();" />
<p>Den totala summan är</p>
<input type="text" value="0" id="svar" />
</form>
<script>
function kalkylera() {
//Get the two numbers entered in the box
var ForstaTalet = document.getElementById("tal1").value;
var AndraTalet = document.getElementById("tal2").value;
//Count the two entered numbers together
var svar = tal1 + tal2;
//Show result
document.getElementById("svar").value = svar;
}
</script>
PS, I'm not sure why "//# sourceURL=pen.js" is written i the bottom of the calculator when adding this to the codepen, that is not how it looks when viewing it in chrome.
Thanks in advance.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" placeholder='num1' id="tal1"/> <br>
<input type="text" placeholder='num2' id="tal2"/> <br>
<input type="button" value="Add" onClick="sum()"/>
<input type="text" placeholder='sum' id="svar"/>
</form>
<script>
function sum()
{
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
var svar = ForstaTalet + AndraTalet;
document.getElementById("svar").value = svar;
}
</script>
</body>
</html>
This works fine.
You need to cast your values as float with parseFloat and use the right variables as in the following example:
//Get the two numbers entered in the box
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
//Count the two entered numbers together
var svar = ForstaTalet + AndraTalet;
//Show result
document.getElementById("svar").value = svar;

I am generating one programm to provide the information that related about lipiniski rule (for drug like molecule ) by providing users values

I am very new in this field. I would like to generate a program which lipinski rule of five that for drug like molecule. This rule has been established one. By providing the entered information, i would like to suggest whether it can be drug molecule or not. I am having problem in function part on my script. i couldnt get any output
<html>
<head>
<h1 align="center"><I><b>Lipinski's rule of five<b></h1>
</head>
<body>
<form name=lipRule>
<b>Hydrogen Bond Donors</b>:<input type="number" name="HBD"><br/>
<b>Hydrogen Bond Acceptors</b>:<input type="number" name="HBA"><br/>
<b>Molecular Weight(dalton)</b>:<input type="number" name="MW"><br/>
<b>LogP</b>:<input type="number" name="LogP"><br/>
<input type="button" value="Result" onClick="lipinskiRule()"></br>
<b>As per your entered values, your drug is:</b><input type="text" name="rule"><br/>
<input type="reset" value="Reset" style=color:purple;font-size:18px; ><br/>
</form>
<script language="Javascript">
<!--
function lipinskiRule()
{
var HBD=document.lipRule.HBD.value
var HBA=document.lipRule.HBA.value
var MW=document.lipRule.MW.value
var LogP=document.lipRule.LogP.value
if(HBD <=5 && HBA <=10 && MW <=500 && LogP <=5)
{
document.write("your drug molecule follows LIPINSKI'S rule")
}
}
else
{
document.lipRule.rule.value="your drug molecule doesn't follows LIPINSKI'S rule"
}
//-->
</script>
<style>
body{background-color:lightblue;}
h1{color:blue;background-color:lightgreen;}
</style>
</html>
You need to convert your value to numbers (in this case with an unary +) and correct the condition, because it ends and takes then another curly bracket for closing.
Then you need a place for the output, without using document.write, because after rendering the page, you can not write somthing to the page with it. You could use an tag with id and take it for the output.
Hint: You could use the convention and use variable names with starting small letter and only starting with capital letters for classes or instanciable functions. All caps variable names denotes constant values.
function lipinskiRule() {
var HBD = +document.lipRule.HBD.value,
HBA = +document.lipRule.HBA.value,
MW = +document.lipRule.MW.value,
LogP = +document.lipRule.LogP.value;
if (HBD <= 5 && HBA <= 10 && MW <= 500 && LogP <= 5) {
document.getElementById('conclusion').innerHTML = "your drug molecule follows LIPINSKI'S rule";
} else {
document.getElementById('conclusion').innerHTML = "your drug molecule doesn't follows LIPINSKI'S rule";
}
}
body { background-color: lightblue; }
h1 { color: blue; background-color: lightgreen; }
<h1 align="center">Lipinski's rule of five</h1>
<form name=lipRule>
<b>Hydrogen Bond Donors</b>:<input type="number" name="HBD"><br/>
<b>Hydrogen Bond Acceptors</b>:<input type="number" name="HBA"><br/>
<b>Molecular Weight(dalton)</b>:<input type="number" name="MW"><br/>
<b>LogP</b>:<input type="number" name="LogP"><br/>
<input type="button" value="Result" onClick="lipinskiRule()"></br>
<b>As per your entered values, your drug is:</b><input type="text" name="rule"><br/>
<input type="reset" value="Reset" style=color:purple;font-size:18px; ><br/>
</form>
<p id="conclusion"></p>

Round value using selection of drop down menu / radio button

This consists of two problems. The first problem is rounding numbers to a certain decimal point. The second problem is connecting the drop down menu to the right decimal.
First my code:
<style>
span{font-style:italic;}
span{color:green;}
</style>
<script>
function calcul(){
var sales = parseFloat(document.getElementById("sales").value);
var OpExp = parseFloat(document.getElementById("OpExp").value);
var TaxAll = parseFloat(document.getElementById("TaxAll").value);
var Depre = parseFloat(document.getElementById("Depre").value);
var Divid = parseFloat(document.getElementById("Divid").value);
var TaxR = parseFloat(document.getElementById("TaxR").value);
//GP = Gross Profit
var GP = sales - OpExp;
//TaxInc = Taxable Income
var TaxInc = GP + TaxAll;
//NetInc = Net Income
var NetInc = TaxInc - ((TaxR / 100) * TaxInc);
document.getElementById("NetIncome").innerHTML=
TaxInc - ((TaxR / 100) * TaxInc);
//AtRE = Addition to Retained Earnings
document.getElementById("AtRE").innerHTML = NetInc - Divid;
}
</script>
<form action="" id="nothing">
In 2007 the British building firm Balfour Betty plc had sales of
<input type="text" id="sales" maxlength="6" size="6">
million, total operating expenses of
<input type="text" id="OpExp" maxlength="6" size="6">
million, a tax allowance (rebate) of
<input type="text" id="TaxAll" maxlength="6" size="6">
million because of past losses, and
<input type="text" id="Depre" maxlength="6" size="6">
depreciation. <strong>What is the net income of the
firm?</strong><br />
<br />
Balfour Betty plc paid out <input type="text" id="Divid" maxlength="6" size="6"> million
in cash dividends. <strong>What is the addition to retained earnings?</strong><br />
<br />
The tax rate is <input type="text" id="TaxR" maxlength="6" size="6"> %.<br />
<br />
<input type="button" value="Calculate" id="but" onclick="calcul()" /><br />
<br />
</form>
<strong>The Net Income of Balfour Betty plc is </strong><span id="NetIncome">XXX</span>
<strong> million</strong><br />
<br />
<strong>The addition to retained earnings of Balfour Betty plc is </strong><span id="AtRE">
XXX</span><strong> million</strong>
<br />
<br />
The first problem: rounding numbers. The following answer: <span id="NetIncome"> needs to be rounded dynamically. I've tried to add a new variable called RNetInc and add the following equation RNetInc = NetInc.toFixed(4), but it only gave me two decimals, and after a refresh it doesn't even work anymore. What is the best way to round the answer to N decimals?
The second problem is one I don't know if it's possible. What I have in mind is the following:
A dropdown menu
<select>
<option value"1">1 decimal</option>
<option value"2">2 decimals</option>
<option value"3">3 decimals</option>
</select>
So, what I want is that when I click N decimal, the answer will change to N decimal. This is a very complex situation, but one I often need.
Since I only know the (very) basics of Javascript, even using Google I cannot find the answer. Can someone get me on the right track (if it's even possible)? Thanks in advance.
I'd suggest to fix only the final results, toFixed() returns a string.
HTML for select:
<select id="dec">
<option value="1">1 decimal</option>
<option value="2">2 decimals</option>
<option value="3">3 decimals</option>
</select>
In calcul():
var decs = +(document.getElementById('dec').value); // Add this line
document.getElementById("NetIncome").innerHTML = (TaxInc - ((TaxR / 100) * TaxInc)).toFixed(decs);
document.getElementById("AtRE").innerHTML = (NetInc - Divid).toFixed(decs);
A live demo at jsFiddle (updated).
EDIT
Looks like I've partially missunderstood your question. Please check the updated fiddle, now you can also change the amount of decimals at any time by picking a value from select.

What's wrong with this code water boiling project

I'm doing this for a class. The point is to show how to boil water in programming... idk it's weird but you can look at my code and see what's up. It has a purpose but I don't have time to explain. please don't make any big changes. I want it to run the way it is not how it should be done or whatever. I'm not the best with javascript so please don't judge as much.
issue
it the first input works fine so no worries about that. It's my form that has issues.... what's supposed to happen is I type one of the variables in and it'll display what ever pour says. But when I go to submit it doesn't work whatsoever... just restarts the page! I give so far.... because I obviously don't know what's wrong :P something stupid probably. Thanks!
code
<html>
<head>
<title>
Boiling Water
</title>
</head>
<body bgcolor='#000000'>
<center>
<font color='#ffffff' size='8'><b>D.W.B.A</b>
<br>
Digital</font> <font color='#00ffff' size='8'>Water</font><font color='#ffffff' size='8'> Boiling Association</font>
<br>
<font size='3' color='#ffffff'>Programmed in JavaScript</font>
<br>
<br>
<br>
<p><font color='#ffffff' size='4'>Grab 1 of 56 Cups From the Kitchen Cabinet!</font></p>
<font color='#ff0000' size='4'><p id="cup"><input type='button' value='Obtain Cup' onclick='cup()' /></p></font>
<script>
function cup() {
var cabinet=56;
var quantity=55;
var obtain=cabinet-quantity;
var cupP=document.getElementById("cup")
cupP.innerHTML="You have Obtained " + obtain + " Cup";
}
</script>
<script>
function fill() {
var x=document.getElementById("calculate").value;
var optionzero=0;
var optionone=25;
var optiontwo=50;
var optionthree=75;
var optionfour=100;
if (optionzero) {
pour="Please Pour contents into your Cup";
} else if (optionone) {
pour="You have filled the Cup 1/4 of the way with water";
} else if (optiontwo) {
pour="You have filled the Cup 2/4 or 1/2 of the way with water";
} else if (optionthree) {
pour="You have filled the cup 3/4 of the way with water";
} else if (optionfour) {
pour="Your cup is filled (4/4 of the way) with water";
}
document.getElementById("fillup").innerHTML=pour;
}
</script>
<br>
<form type='input' >
<font color='#ffffff' size='4'>Fill the Cup with Water per 25% out of 100% Ex) 25%, 75%, etc. </font>
<br>
<br>
<input type='text' id='calculate'>
<br>
</form>
<input type='submit' value='Calculate' onclick='fill()' />
<br>
<font color='#ffffff'><p id='fillup'>
</p></font>
</center>
</body>
</html>
Simply try not submitting the form. You can either return false; from the fill function and change your inline handler to onclick='return fill()' or simply change the whole input for:
<button type='button' onclick='fill()'>Calculate</button>
Submitting the form is mostly useful when you want to send information to a server-side process which you don't need to do there.
Your form is submitting to the current page. You should probably move your fill() to onsubmit for the form. Also, make sure that function returns false, or the form will still submit.

Javascript/Ajax/Jquery Dynamically calculate form on change

I have a small form which is going to be populated from Mysql and human input. What I want to do is populate 3 other fields based on the other ones.
Example:
Total Parts (Mysql)
Labor (User)
Misc (User)
Sub Total (Dynamic total of above)
Tax (Dynamic calc of above - sub * 13%)
Total (Sub + Tax)
I have searched around but can not quite find what I am looking for, and my skills are zero in Javascript/Ajax/Jquery so I haven't been able to modify anything to work, although I have tried miserably.
Can someone help me out on this or point me to a script that may suit my needs.
Thanks
Alright sorry, I thought you were looking for some complex code. Here is a simple example of exactly what you're looking for.
<html>
<head>
</head>
<body>
<script>
function doMath() {
var totalparts = parseInt(document.getElementById('parts_input').value);
var labor = parseInt(document.getElementById('labor_input').value);
var misc = parseInt(document.getElementById('misc_input').value);
var subtotal = totalparts + labor + misc;
var tax = subtotal * .13;
var total = subtotal + tax;
document.getElementById('subtotal_input').value = subtotal;
document.getElementById('tax_input').value = tax;
document.getElementById('total_input').value = total;
}
</script>
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
<div>Labor: <input type="text" id="labor_input" onBlur="doMath();" /></div>
<div>Misc: <input type="text" id="misc_input" onBlur="doMath();" /></div>
<div>Sub Total: <input type="text" id="subtotal_input" readonly="true" /></div>
<div>Tax: <input type="text" id="tax_input" readonly="true" /></div>
<div>Total: <input type="text" id="total_input" readonly="true" /></div>
</body>
</html>
Obviously this doesn't grab the dynamic value from a database. If you use PHP you can swap this line:
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
for one like this:
<div>Total Parts: <input type="text" id="parts_input" value="<?PHP include('getTotalParts.php'); ?>" readonly="true" /></div>
Where the getTotalParts.php is a file you make to get your database information. It can simply grab the information and do a "echo $totalParts;"
You can just use onblur (activated when a user leaves each of the input fields) to calcuate the fields.
...<input name="labour" id=total onblur="$('#total').val($('#sub').val() + $('#tax').va())">
You haven't provided enough information to comment on the "Total Parts" field.

Categories