The image above is a screenshot of a BMI calculator I'm working on at the moment.
The JavaScript code below is supposed to convert value supplied in the feet label (ftheight) box into inches and then add it up to value supplied into the Inches label (inheight) then multiply the result by 2.54 to convert it to centimeters(cm).
The BMI result given is wrong if for example, Weight is 75kg, Height is 5ft 9", BMI result shows 0.31 instead of 24.42. But when I changed the value for feet to 0 or blank and value for inches to 69, it gave the correct result of 24.42
HTML
<form name="bmiForm">
Your Weight(kg): <br><br>
<input type="text" name="weight" size="10"><br />
Your Height: <br><br>
Feet: <input type="number" name="ftheight" size="10">
Inches: <input type="number" name="inheight" size="10"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()"><br /><br />
Your BMI: <br><input class="bmiresult" name="bmi" size="10"><br />
This Means: <br><input class="bmimean" name="meaning" size="25"><br />
<input type="reset" value="Reset" /> </form>
JAVASCRIPT
function calculateBmi() {
var weight = document.bmiForm.weight.value
var result = 2.54 * (document.bmiForm.ftheight.value * 12 + document.bmiForm.inheight.value)
var height = result
if(weight > 0 && height > 0){
var finalBmi = weight/(height/100*height/100)
document.bmiForm.bmi.value = finalBmi
if(finalBmi < 18.5){
document.bmiForm.meaning.value = "Hmm... you are too thin."
}
if(finalBmi > 18.5 && finalBmi < 25){
document.bmiForm.meaning.value = "Yah! you are healthy."
}
if(finalBmi > 25){
document.bmiForm.meaning.value = "Oops... you are overweight."
}
}
else{
alert("Please Fill in everything correctly")
}
}
What I want is to first convert value supplied into the feet box into inches and add it up to the value supplied in the Inches box and multiply the result by 2.54 to give me value for var height
I changed the weight input to type number (to keep it consistent with other inputs), and then called parseFloat on the input values (as input values are usually stored as text by default, not numbers).
You could change this to be parseInt for ft and inch values if you want to restrict the values to integers though.
If you find that the output is "ugly", you can constrain the number of decimals you show in the result by using toFixed as well.
function calculateBmi() {
var weight = parseFloat(document.bmiForm.weight.value);
var ftHeight = parseFloat(document.bmiForm.ftheight.value);
var inHeight = parseFloat(document.bmiForm.inheight.value);
var height = 2.54 * (ftHeight * 12 + inHeight);
if(weight > 0 && height > 0){
var finalBmi = weight / (height / 100 * height / 100)
document.bmiForm.bmi.value = finalBmi
if(finalBmi < 18.5){
document.bmiForm.meaning.value = "Hmm... you are too thin."
} else if(finalBmi > 18.5 && finalBmi < 25){
document.bmiForm.meaning.value = "Yah! you are healthy."
} else if(finalBmi > 25){
document.bmiForm.meaning.value = "Oops... you are overweight."
}
} else{
alert("Please Fill in everything correctly")
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form name="bmiForm">
Your Weight(kg): <br><br>
<input type="number" name="weight" size="10"><br />
Your Height: <br><br>
Feet: <input type="number" name="ftheight" size="10">
Inches: <input type="number" name="inheight" size="10"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()"><br /><br />
Your BMI: <br><input class="bmiresult" name="bmi" size="10"><br />
This Means: <br><input class="bmimean" name="meaning" size="25"><br />
<input type="reset" value="Reset" />
</form>
</body>
</html>
I'm not sure what you're doing wrong, but this worked for me https://jsfiddle.net/vxshwk2w/
Try using id instead of name.
Related
the button wont submit the code and return the if statement
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>Body Mass Calculator</title>
</head>
<body>
<h1>Body Mass Calculator</h1>
<br>
<h3>Today, we're going to calculate your body's BMI.</h3>
<br>
<form>
<label for="height">Height</label>:
<input type="number" id="feet" min="1" max="9" step="1" required><label for="feet"> Feet</label>
<input type="number" id="inches" min="0" max=".11" step=".01" required><label for="inches"> Inches</label>
<br>
<br>
<label for="weight">Weight</label>:
<input type="number" id="weight" min="0" max="1400" step=".01"required><label for="weight"> Pounds</label>
<br>
<br>
<input type="button" id="submit" value="Submit">
</form>
<br>
<br>
<h1 id="finalResult"></h1>
<img id="img" src="" height="auto" width="500px">
<script src="js/script.js"></script>
</body>
</html>
//[weight (lb) / height (in) / height (in)] x 703
document.querySelector("#submit").addEventListener("click", function (e) {
if (document.querySelector("#feet").reportValidity() &&
document.querySelector("#inches").reportValidity() &&
document.querySelector("#weight").reportValidity()) {
let heightFeet = parseFloat(document.querySelector("#feet").value);
let heightInches = parseFloat(document.querySelector("#inches").value);
let height = (heightFeet * 12) + (heightInches * 10);
let weight = parseFloat(document.querySelector("#weight").value);
let bmi = (weight / height / height) * 703;
if (bmi < 18.5) {
document.querySelector("#finalResult").innerHTML = `Your BMI is ${bmi}, indicating your weight is in the UNDER WEIGHT RANGE for adults of your height.`
document.querySelector("#img").src = "/img/underWeight.jpg";
}
else if(bmi < 24.9 && bmi >= 18.5){
document.querySelector("#finalResult").innerHTML = `Your BMI is ${bmi}, indicating your weight is in the HEALTHY WEIGHT RANGE for adults of your height.`
document.querySelector("#img").src = "/img/healthyWeight.jpg";};
else if(bmi < 29.9 && bmi >= 24.9){
document.querySelector("#finalResult").innerHTML = `Your BMI is ${bmi}, indicating your weight is in the OVER WEIGHT RANGE for adults of your height.`
document.querySelector("#img").src = "/img/overWeight.jpg";};
else if(bmi<35 && bmi >=29.9>){
document.querySelector("#finalResult").innerHTML = `Your BMI is ${bmi}, indicating your weight is in the OBESE WEIGHT RANGE for adults of your height.`
document.querySelector("#img").src = "/img/obeseWeight.jpg";};
else if(bmi>= 35){
document.querySelector("#finalResult").innerHTML = `Your BMI is ${bmi}, indicating your weight is in the EXTREME OBESE WEIGHT RANGE for adults of your height.`
document.querySelector("#img").src = "/img/extremeObeseWeight.jpg";};
else{
alert("ERROR!")
};
}
});
the h1 and the img should be appearing after clicking the button with the correct low bmi entered for the if statement, but nothing is happening. im not getting the validation checks either.
the way the code is worded is as it has to be for the class. i cannot add things or rewrite the code using a different methodologies that have not been taught in this class.
Your code had multiple errors that were shown in the console. Always check the browser's console first for any suspicious messages.
After fixing all the errors, your function works.
<script>
document.querySelector("#submit").addEventListener("click", function (e) {
if (document.querySelector("#feet").reportValidity() &&
document.querySelector("#inches").reportValidity() &&
document.querySelector("#weight").reportValidity()) {
let heightFeet = parseFloat(document.querySelector("#feet").value);
let heightInches = parseFloat(document.querySelector("#inches").value);
let height = (heightFeet * 12) + (heightInches * 10);
let weight = parseFloat(document.querySelector("#weight").value);
let bmi = (weight / height / height) * 703;
if (bmi < 18.5) {
document.querySelector("#finalResult").innerHTML = `Your BMI is ${bmi}, indicating your weight is in the UNDER WEIGHT RANGE for adults of your height.`
document.querySelector("#img").src = "/img/underWeight.jpg";
}
}
});
</script>
This is a BMI calculator. I expect to check the data validation first. text fields cannot be empty. And then calculate the BMI and display into another text box.. Validation part is working properly, but the calculating function is not. Please help me to find the error.
function validate() {
if (document.myForm.weight.value == "") {
alert("Please provide your weight!");
document.myForm.weight.focus();
return false;
}
if (document.myForm.height.value == "") {
alert("Please provide your heught!");
document.myForm.height.focus();
return false;
}
calBMI();
}
function calBMI() {
var weight = getElementById("weight").value;
var height = getElementById("height").value;
var bmi = weight / (height * height);
document.getElementById("bmi").innerHTML = bmi;
}
<body>
<form name="myForm">
<label>weight</label>
<input type="text" name="weight" id="weight">
<label>height</label>
<input type="text" name="height" id="height">
<input type="text" readonly="readonly" id="bmi">
<input type="submit" value="Submit" onclick="validate() calBMI()">
</form>
</body>
function validate() {
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
if (height == "" || height == 0) {
document.getElementById("result").innerHTML = "Please enter a valid height";
return;
}
if (weight == "" || weight == 0) {
document.getElementById("result").innerHTML = "Please enter a valid weight";
return;
}
calBMI();
}
function calBMI() {
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var bmi = weight / (height * height);
document.getElementById("result").innerHTML = `BMI: ${bmi}`;
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div>Weight</div>
<input type="number" id="weight">
<div>Height</div>
<input type="number" id="height">
<input type="submit" value="Submit" onclick="validate()">
<div id="result"></div>
</body>
</html>
Add proper functions to calculate bmi. No need to call calculatebmi on submit.
var form = document.getElementsByName('myForm')[0];
form.addEventListener('submit', validate);
function validate(e) {
e.preventDefault();
if (document.myForm.weight.value == "") {
alert("Please provide your weight!");
document.myForm.weight.focus();
return false;
}
if (document.myForm.height.value == "") {
alert("Please provide your heught!");
document.myForm.height.focus();
return false;
}
var weight = document.myForm.weight.value;
var height = document.myForm.height.value;
calBMI(weight, height);
return true;
}
function calBMI(w, h) {
var bmi = Math.ceil((w / Math.pow(h, 2)) * 703);
document.getElementById("bmi").setAttribute('value', bmi);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form name="myForm">
<label>weight</label>
<input type="text" name="weight" id="weight">
<label>height</label>
<input type="text" name="height" id="height">
<input type="text" readonly="readonly" id="bmi">
<input type="submit" value="Submit" onclick="validate();">
</form>
</body>
</html>
When I run the code on my chrome browser, clicking the calculate button, it does not put the value in the Total and Sales Tax text box.
Also "Add the Javascript event handler for the click event of the Clear button, This should clear all text boxes and move the cursor to the Subtotal field."
I'm using Html and js file. Using a function expression to calculate and display my calculation, then also use the clear button to clear all text boxes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>
This is my js file.
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.
")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = sumSalesTax;
};
Sales Tax Calculator
It seems like you had a typo when you were doing $("clear").onclick = sumSalesTax;, as the variable was named SumSalesTax rather than with the lower case. This meant that the code block errored out and therefore didn't actually run. Make sure you make good use of the browser console so you can spot errors like this! The below example should work
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = SumSalesTax;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>
I have been working with a javascript that will calculate BMI of a person. But with the BMI result, I want to display specific comments of specific result group. How can I do that?
Here is the script:
<script>
<!--
function calculateBmi()
{
var weight = document.bmiForm.weight.value
var height = document.bmiForm.height.value
if(weight > 0 && height > 0)
{
var stadnardwight1 = 19*height/100*height/100
document.bmiForm.weight1.value = stadnardwight1
var stadnardwight2 = 25*height/100*height/100
document.bmiForm.weight2.value = stadnardwight2
var finalBmi = weight/(height/100*height/100)
document.bmiForm.bmi.value = finalBmi
if(finalBmi < 19)
{
document.bmiForm.meaning.value = "That you are too thin."
}
if(finalBmi > 19 && finalBmi < 25)
{
document.bmiForm.meaning.value = "That you are healthy."
}
if(finalBmi > 25)
{
document.bmiForm.meaning.value = "That you have overweight."
}
}
else
{
alert("Please Fill in everything correctly")
}
}
//-->
</script>
<form name="bmiForm">
Your Weight(kg): <input type="text" name="weight" size="10"><br />
Your Height(cm): <input type="text" name="height" size="10"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()"><br />
Your BMI: <input type="text" name="bmi" size="10"><br />
This Means: <input type="text" name="meaning" size="25"><br />
Your weight should be between: <input type="text" name="weight1" size="10"> to <input type="text" name="weight2" size="10"> kg<br />
<input type="reset" value="Reset" />
</form>
Here, meaning value is displayed by a text input from. But how can I display it as a paragraph, not as a text input?
Thanks in advance for helping.
Note: The meaning will change according to the 3 different categories of results.
It would be very helpful if you please give an example of line of code for the solution.
Instead of using an 'input' tag for meaning, use a 'span' tag, and set the innerHtml of that span to the content you want.
So basically, I am creating an application form for gym membership.
The base cost is $100. If juggling is selected, the cost will increase by $50.
Also, the base cost will increase by $50 if the 'BMI' is > 25 and <= 30. If the 'BMI' is > 30, it will increase by $100 instead.
This is my code. It is not working as intended. Would like some help. Thanks a lot.
<!DOCTYPE html>
<html>
<head>
<title>UWS application form</title>
<link rel="stylesheet" href="Prac1Task2.css" />
</head>
<body>
<form>
<fieldset>
<legend>Fitness Details</legend>
Favourite Activities: <br/>
<input type="checkbox" name="activity" value="cycling" id="cycling"><label for="cycling">Cycling</label>
<input type="checkbox" name="activity" value="50" id="juggling" onchange="update(this);"><label for="juggling">Juggling</label>
<br/>
<br/>
<label for="height">What is your height (Meters)</label><br/>
<input type="number" name="height" id="height" class="input" onchange="getBMI()">
<br/>
<label for="weight">What is your weight? (kg)</label><br/>
<input type="number" name="weight" id="weight" class="input" onchange="getBMI()">
<br/>
<label for="bmi">BMI:</label><br/>
<input type="number" name="bmi" id="bmi" class="input" value="" readonly>
<script>
function getBMI()
{
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
document.getElementById("bmi").value = (weight / height) / height;
var bmi = document.getElementById("bmi");
var price = document.getElementById("price").value;
if (bmi.value > 25 && bmi.value <= 30)
{
parseInt(price.value) += parseInt(50);
document.getElementById('price').value = price.value;
}
else if (bmi.value > 30)
{
document.getElementById("price").value = document.getElementById("price").value + 100;
}
}
</script>
</fieldset>
<br/>
<fieldset>
<legend>Application Details</legend>
Date of Application:<br/>
<input class="input" id="date" name="date" readonly />
<script>
var timetime = new Date();
document.getElementById("date").value = (timetime.getDate() + "/" + (timetime.getMonth() + 1)
+ "/" + timetime.getFullYear());
</script>
<br/><br/>
Cost of Application: <br/>
$<input type="number" class="input" id="price" name="price" step="0.01" value="100" readonly />
<script>
var total = 100;
function update(feature) {
if(feature.checked == true){
total += parseInt(feature.value);
document.getElementById('price').value = total;
}
if(feature.checked == false){
total -= parseInt(feature.value);
document.getElementById('price').value = total;
}
}
</script>
</fieldset>
<br/>
<input type="submit" value="Submit" class="button">
</form>
</body>
</html>
You haven't mentioned the exact issue which you are facing. However, I think there should be some problem with this line of code.
parseInt(price.value) += parseInt(50);
parseInt() is a function and you cannot assign values to it.
It should be some thing like this
price.value = parseInt(price.value) + parseInt(50);
Also price.value is not a proper reference because you are assigning document.getElementById("price").value; to it. So you should be using price instead of price.value