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>
Related
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 am new to Javascript and just getting into it for my web design class. I am working on a project with Javascript inside HTML. I have it all written, but the HTML doesn't seem to call the Javascript function. I've been searching for a solution but can't seem to get anything to work. The code is:
<html>
<head>
<script>
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
message-box ("Invalid data for principle amount.");
}
}
else {
message-box ("Invalid data for interest rate.");
}
}
</script>
<style>
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
</style>
</head>
<body>
<form>
Enter Principal Ammount : <input type="text" id ="principal" />
</br>
Enter Intrest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Ammount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick=calculateInterest()/> </br>
</form>
</body>
</html>
The browser error is "SyntaxError: expected expression, got '}' " on line 2 but I just can't see what the issue is. Any help is greatly appreciated!
Side note, I am aware there are some weird spelling mistakes. My instructor is from India and not totally fluent in English. She made the HTML file for us to use and we just have to put in the Javascript.
There is no message-box function. Did you mean alert()? Your code currently works, with those changes:
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
alert("Invalid data for principle amount.");
}
}
else {
alert("Invalid data for interest rate.");
}
}
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
<form>
Enter Principal Amount : <input type="text" id ="principal" />
</br>
Enter Interest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Amount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick="calculateInterest()" /> </br>
</form>
Small Nitpick: Fixed some small typos not related to code. Ammount => Amount. Intrest => Interest.
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.
The value for 2nd 3rd and 4th box is fixed as 100 50 50 if the user enters 300 the value should split it into 100 50 50 and remaining 100 should be in balance box...
suppose if the user enters 100 it should fill the first box other box should be zero..
suppose if the user enters 50 it should fill the second box other box should be zero.. like tat i had tried the following code but it has error...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
window.update = function() {
var one = document.getElementById('one'),
two = document.getElementById('two');
three = document.getElementById('three');
four = document.getElementById('four');
five = document.getElementById('five');
two.value = parseInt(one.value) - 100;
//if(two.value < 100)
// {
three.value = parseInt(two.value) - 50;
//}
//if(two.value > 100)
//{
// three.value = parseInt(two.value) - 0;
four.value = parseInt(three.value) - 50;
//}
five.value = parseInt(three.value) - 50;
}
function checknumber(txtid) {
var mynumbervalue = parseFloat((txtid).value);
if (mynumbervalue > 100) {
txtid.value = "0";
alert("Please try again. Values must be between 0-100...");
}
if (theid.value < 0) {
txtid.value = "0";
alert("Please try again. Values must be between 0-100 ...");
}
}
</script>
</head>
<body><br><p align="center">
Enter the amount to be paid<input id="one" type="text" onChange="update();" /><br>
book fees<input id="two" type="text" name="txt" onchange="checknumber(this)"/> 100<br>
uniform fees<input id="three" type="text" /> 50<br>
Bus fees<input id="four" type="text" /> 50<br>
balance fees<input id="five" type="text" /> <br>
</p>
</body>
</html>