I'm trying to create a heart rate zone calculator but it won't display the result of the calculation. I am new to javascript and html (coming from a java background) so any help and constructive criticism with that in mind is appreciated!
<html>
<head>
<title>BMI Calculator</title>
<script type="text/javascript">
function CalculateBMI()
{
//Obtain user inputs
var Intensity = Number(document.getElementById("Intensity").value);
var select_intensity = document.getElementById("select_intensity").value;
var Age = Number(document.getElementById("Age").value);
//Perform calculation based on intensity
if (select_intensity == "Moderate") {
var output = (220-Age)*.5;
var output2 = (220-Age)*.7;
}
if (select_intensity == "High Intensity") {
output = (220 - Age) * .7;
output2 = (220 - Age) * .85;
}
//Display result of calculation
document.getElementById("output").innerHTML=output " to " output2;
}
</script>
</head>
<body>
<h1>Heart Rate Zone Calculator</h1>
<p>Select Your Workout Intensity: <select type="multiple" id="Intensity">
<option value="Moderate"selected="selected">Moderate</option>
<option value="High Intensity">High Intensity</option>
</select>
</p>
<p>Enter your age: <input type="text" id="Age"/>
</p>
<input type="submit" value="Calculate Target Heart Rate" onclick="CalculateBMI();">
<h1>Your Target Heart Rate Zone Is: <span id="output" >?</span></h1>
</body>
You have a couple of issues with your Javascript:
1) You have 2 intensity variables:
var Intensity = Number(document.getElementById("Intensity").value);
var select_intensity = document.getElementById("select_intensity").value;
Intensity refers to the correct element, but all of your code seems to only reference the select_intensity variable. Do this instead:
var select_intensity = document.getElementById("Intensity").value;
2) You forgot to place + around the " to " string for concatenation.
document.getElementById("output").innerHTML=output + " to " + output2;
Fixing both of those issues should cause it to work.
Remove
var Intensity = Number(document.getElementById("Intensity").value);
and change
var select_intensity = document.getElementById("Intensity").value;
to
var select_intensity = document.getElementById("select_intensity ").value;
Also change this
document.getElementById("output").innerHTML=output + " to " + output2;
This is finally how your code should look like
<html>
<head>
<title>BMI Calculator</title>
<script type="text/javascript">
function CalculateBMI()
{
//Obtain user inputs
//var Intensity = Number(document.getElementById("Intensity").value);
var select_intensity = document.getElementById("Intensity").value;
var Age = Number(document.getElementById("Age").value);
//Perform calculation based on intensity
if (select_intensity == "Moderate") {
var output = (220-Age)*.5;
var output2 = (220-Age)*.7;
}
if (select_intensity == "High Intensity") {
output = (220 - Age) * .7;
output2 = (220 - Age) * .85;
}
//Display result of calculation
document.getElementById("output").innerHTML=output + " to " + output2;
}
</script>
</head>
<body>
<h1>Heart Rate Zone Calculator</h1>
<p>Select Your Workout Intensity: <select type="multiple" id="Intensity">
<option value="Moderate"selected="selected">Moderate</option>
<option value="High Intensity">High Intensity</option>
</select>
</p>
<p>Enter your age: <input type="text" id="Age"/>
</p>
<input type="submit" value="Calculate Target Heart Rate" onclick="CalculateBMI();">
<h1>Your Target Heart Rate Zone Is: <span id="output" >?</span></h1>
</body>
smaili's answer sums it up. I'd just like to add that as a new javascript programmer, you'll wanna be familiar with console.log() and F12 in your browser (unless you have a full-on JS dev IDE).
Related
<!DOCTYPE html>
<html>
<head>
<title>
Unit 2 Graded Exercise 1
</title>
</head>
<body>
<header>
<h1>Unit 2 Graded Exercise 1</h1>
<br/>
</header>
<form>
<fieldset>
<label for="price" id="label">Purchase Price</label>
<input type="text" id="partPrice" />
<button type="button" id="button">Calculate Shipping and Handling</button>
</fieldset>
</form>
</body>
<script>
var partPrice = document.getElementById("partPrice").value;
var totalPrice;
function calcTotal() {
if (partPrice <= 25) {
var totalPrice = partPrice + 1.5; //price + sh
} else if (partPrice > 25) {
var totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price
}
alert("Shipping and Handling is $" + totalPrice);
}
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", calcTotal, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
</script>
</html>
So my goal is to show interest + $1.50 for a total cost below or equal to $25 and 10% interest of a total cost above $25. My problem is that the "partPrice", which is the price that the user enters, is not being received. I've looked up quite a bit about this and I've seen people go around by creating multiple variables to pick up certain values but I have yet to understand why. I would really like an explanation because, going through this code, it all looks logically correct. I'm really lost as to where I should be changing my syntax.
Update your code to following
Move the get value code inside the function
Convert the value which is a string to a number
function calcTotal() {
var partPrice = parseFloat(document.getElementById("partPrice").value);
...
}
Just get data inside function. also remove variable declaration in if statement
<html>
<head>
<title>
Unit 2 Graded Exercise 1
</title>
</head>
<body>
<header>
<h1>Unit 2 Graded Exercise 1</h1>
<br/>
</header>
<form>
<fieldset>
<label for="price" id="label">Purchase Price</label>
<input type="text" id="partPrice" />
<button type="button" id="button">Calculate Shipping and Handling</button>
</fieldset>
</form>
</body>
<script>
var partPrice,
totalPrice;
function calcTotal() {
partPrice = document.getElementById("partPrice").value;
if (partPrice <= 25) {
totalPrice = partPrice + 1.5; //price + sh
} else if (partPrice > 25) {
totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price
}
alert("Shipping and Handling is $" + totalPrice);
}
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", calcTotal, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
</script>
</html>
var partPrice = document.getElementById("partPrice").value;
This line is executed once when the script is loaded, so partPrice will be an empty string. It doesn't get reevaluated automatically when you write anything in input, so you'll have to call document.getElementById("partPrice").value again in calcTotal to fetch the current value of partPrice.
this is an exercise from Murach's Javascript and Jquery book. An income tax calculator. The code is pretty self explanatory. The error: undefined is popping up where the value of the tax owed should be. commented out if statement outputted the same 'undefined' error. The documentation said, undefined usually is outputted when a variable isn't assigned or returned and i've done all that.
JS
"use strict";
var $ = function (id) {
return document.getElementById(id);
};
var income;
var taxOwed;
var calculateTax = function(income){
/*if (income > 0 && income < 9275){
//incomeTax = taxableIncome - 0;
//percentIT = incomeTax * (10/100);
taxOwed = (income - 0) * (10/100) + 0;
taxOwed = parseFloat(taxOwed);
taxOwed = taxOwed.toFixed(2); //the tax should be rounded two
return taxOwed;
}*/
if (income < 9275){
taxOwed = income - 0 * .10 + 0;
}else if(income > 9275){
taxOwed = ((income - 9275) * .15) + 927.50;
}
return taxOwed;
};
var processEntry = function(){
income = parseInt($("income").value); //users entry should be converted
if(isNaN(income)){
alert("Entry must be a number");
}else if (income <= 0){
alert("income must be greater than 0");
}else{
$("taxOwed").value = calculateTax(income);
}
};
window.onload = function () {
$("calculate").onclick = processEntry;
$("income").focus();
};
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ace</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Income Tax Calculator</h1>
<label>Enter taxable income:</label>
<input type="text" id="income" /> <!--income is variable name for taxable income-->
<input type="button" value="Calculate" name="calculate" id="calculate" /><br><br>
<label>Income tax owed:</label>
<input type="text" id="taxOwed"><br> <!--tax is variable name for taxOwed*-->
<script src="calculate_tax.js"></script>
</body>
</html>
You probably aren't passing anything in. put a debugger statement after income and open your dev console, check if the variable actually has a value.
//use val() not value
income = parseInt($("income").val());
debugger;
my javascript gives a estimate for name plates
each letter is $10
Very new to Javascript, I am trying to get rid of the text Area on my input/display once the submit/button is clicked. . . . lets just say if I want to re-enter an input it should clear the last input and give new price . . . right now is piling up
for example : Enter Name: Total Cost is $30Total Cost is $60Total Cost is $60Total Cost is $90Total Cost is $110Total Cost is $140
<body>
<div id='container' >
<div id='banner'>
<h4 id='signName'>Name Plate Estimate</h4>
</div>
<p id="enterName">Enter Name: </p>
<div id='form'>
<form>
<input id="userInput" name="userInput" type="text" />
<br>
</form>
</div>
<button id="button">Show Cost</button>
</div>
</body>
heres my javascript ;
document.getElementById('button').onfocus = function(){
var userText = document.getElementById('userInput').value ;
var cost = 10 ;
var price = function(){
var total = userText.length * cost;
return total ;
}
if (userText.length === 0){
var elError = document.getElementById('enterName') ;
elError.innerHTML += "Please enter a valid name" ;
} else {
var elErrror = document.getElementById('enterName') ;
elErrror.innerHTML += 'Total Cost is $' + price() ;
}
}
You are appending the new data to your element with +=, you want to replace the whole innerHTML, so just use the = operator.
elErrror.innerHTML += 'Total Cost is $' + price() ;
becomes
elErrror.innerHTML = 'Total Cost is $' + price() ;
Please add below script:
document.getElementById('userInput').onfocus = function(){
document.getElementById('userInput').value = ''
};
I want my user when they click on “view age” button to calculate there age from there input, but i couldn't figure it out. I got the user to view there birth year when they click on the but.
Here is my HTML Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="birth">
<h2>What month were you born?</h2><input name="birthMonth" type="text" size="20">
<h2>What day was you born?</h2><input name="birthday" type="text" size="20">
<h2>Your birth year?</h2> <input name="birthYear" type="text" size="20">
</form>
<button onclick="outputbirth()">Submit</button>
<button onclick="submitBday()">View Age</button>
<p id="output"></p>
<p id="age"></p>
<script type="text/javascript" src="scripts/scripts.js"></script>
</body>
</html>
JavaScript Code, function submitBday is the button on the html document:
function outputbirth() {
// Getting the form id "birth"
var x = document.getElementById("birth");
var text = "";
// Getting the users input values of Month, Day, Year.
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + " ";
}
// This is going to print out the result on output id in the html document
document.getElementById("output").innerHTML = text;
}
function submitBday() {
}
You already concatenated a string from the input fields. So what you want to do to calculate the age is to construct a date object from the input fields. Just collect the input fields like you did before in a loop, but do not separate the values by an empty space but use a comma.
var bDay += x.elements[i].value + ",";
Then pass the bDay to a new date object.
var start = new Date(bDay);
Now subtract the just created date from now.
var elapsed = Date.now() - start;
This will give you the age in milliseconds. To calculate the years from milliseconds you could do this.
var age = Math.floor(((((elapsed / 1000) / 60) / 60) /24) / 365);
This will give you the age in years. If you want to find out more about the JS date object check out the moz dev network page on Date.
I left a snipped for you. Have fun.
function submitBday() {
var now = Date.now(),
x = document.getElementById("birth"),
bDay = "",
start,
elapsed,
age;
for (i = 0; i < x.length; i++) {
bDay += x.elements[i].value + ",";
}
start = new Date(bDay);
elapsed = now - start;
age = Math.floor(((((elapsed / 1000) / 60) / 60) /24) / 365);
document.getElementById("age").innerHTML = "You are " + age + " years young.";
}
<form id="birth">
<h2>What month were you born?</h2><input name="birthMonth" type="text" size="20">
<h2>What day was you born?</h2><input name="birthday" type="text" size="20">
<h2>Your birth year?</h2> <input name="birthYear" type="text" size="20">
</form>
<button onclick="submitBday()">View Age</button>
<p id="age"></p>
I'm a total newbie to programming. I've been doing exercises on Codecademy for JavaScript for a little while, but there's obviously huge amounts I still don't know/understand. I've written a few things in those exercises, but nothing that anyone has or would actually use. I was planning on keeping it that way for a little longer, but today at work a chance came up to do a little thing and I wanted to challenge myself so I decided to try it.
The idea is to create a form where people can enter their basic information and have it set them a daily calorie amount that conforms to their weight loss goals. It's based around the Basal Metabolic Rate, the Harris Benedict Equation, and a little twist to fit my company's particular program.
I was able to find the Javascript on Dreamingincode for a basic BMR calculator which I then modified to make the adjustments we need. Somewhere in that process, something has gone wrong. When I save the file as a .html file and then open it in the browser, the form appears and you can fill everything out, but when you click the button, it just refreshes the screen.
I know this is stupid to all of you that actually know what you're doing, but I really want to make this work. If any of you feel like being heroic, please look at what I have and tell me where I screwed up.
<html>
<head>
<title>Daily Calorie Goal</title>
</head>
<body>
<script type="text/javascript" language="javascript">
function Calculate() {
var gender = document.getElementById("gender").value;
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var age = document.getElementById("age").value;
var goal = document.getElementById("goal").value;
if(gender=="male")
{
val1 = 6.23 * weight;
val2 = 12.7 * height;
val3 = 6.8 * age;
dailyDeficit = (goal * 3500) / 90;
result = 66 + val1 + val2 - val3;
cals = result * 1.55;
calMax = cals - dailyDeficit;
}
else if (gender=="female")
{
val1 = 6.23 * weight;
val2 = 4.7 * height;
val3 = 4.7 * age;
dailyDeficit = (goal * 3500) / 90;
result = 655 + val1 + val2 - val3;
cals = result * 1.55;
calMax = cals - dailyDeficit;
}
document.write ('This is your Daily Calorie Goal. To achieve your goal, just consume fewer than this number of calories every day:<b> ' + calMax.toFixed(2) + '</b><br>');
}
</script>
<form action="#">
Gender : <select id="gender"><option value="male">Male</option><option value="female">Female</option></select><br />
Weight (lbs.) : <input type="text" id="weight" /><br />
Height (inches): <input type="text" id="height" /><br />
Age : <input type="text" id="age" /><br />
Goal : <select id="Goal"><option value=5>Lose 5 Pounds</option><option value=10>Lose 10 Pounds</option><option value=15>Lose 15 Pounds</option><option value=20>Lose 20 Pounds</option><option value=25>Lose 25 Pounds</option></select><br />
</fieldset>
<input type="submit" value="Get My Daily Calorie Goal" onclick="Calculate()" />
</form>
</html>
You had one of your ids (Goal) spelled with a capital letter and your button was a submit type so it was trying to submit it to the server.
<html>
<head>
<title>Daily Calorie Goal</title>
</head>
<body>
<script type="text/javascript" language="javascript">
function Calculate() {
var gender = document.getElementById("gender").value;
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var age = document.getElementById("age").value;
var goal = document.getElementById("goal").value;
if(gender=="male")
{
val1 = 6.23 * weight;
val2 = 12.7 * height;
val3 = 6.8 * age;
dailyDeficit = (goal * 3500) / 90;
result = 66 + val1 + val2 - val3;
cals = result * 1.55;
calMax = cals - dailyDeficit;
}
else if (gender=="female")
{
val1 = 6.23 * weight;
val2 = 4.7 * height;
val3 = 4.7 * age;
dailyDeficit = (goal * 3500) / 90;
result = 655 + val1 + val2 - val3;
cals = result * 1.55;
calMax = cals - dailyDeficit;
}
document.write ('This is your Daily Calorie Goal. To achieve your goal, just consume fewer than this number of calories every day:<b> ' + calMax.toFixed(2) + '</b><br>');
}
</script>
<form action="#">
Gender : <select id="gender"><option value="male">Male</option><option value="female">Female</option></select><br />
Weight (lbs.) : <input type="text" id="weight" /><br />
Height (inches): <input type="text" id="height" /><br />
Age : <input type="text" id="age" /><br />
Goal : <select id="goal"><option value=5>Lose 5 Pounds</option><option value=10>Lose 10 Pounds</option><option value=15>Lose 15 Pounds</option><option value=20>Lose 20 Pounds</option><option value=25>Lose 25 Pounds</option></select><br />
</fieldset>
<input type="button" value="Get My Daily Calorie Goal" onclick="Calculate()" />
</form>
</html>
Clearing the screen is a side-effect of document.write. What you probably want is having an element that will contain the text.
After the form element, you can append an holder element:
<div id="result"></div>
You can then set the content of it:
document.getElementById("result").textContent = "This is your daily...";
You just got to change this right here:
var goal = document.getElementById("goal").value;
to this
var goal = document.getElementById("Goal").value;