How to engage different function on different select - javascript

That's my second script ever. I'm learning basics at the same time. I would like to engage different function on different option selected.
I try to give value to different option to use it later where the switch is.
It says cannot set property of null. If someone could explain me what I'm doing wrong it would be amazing. Please forgive me for silly mistakes, 3 days of learning in total, unfortunately theory doesn't work on me if i will not try it.
<html>
<body>
<div>
<h2> Daily calorie intake</h2>
<input type = "number" placeholder = "your height" id = "height" min = "1" max = "230"><p></p>
<input type = "number" placeholder = "your age" id = "age" min = "1" max = "120"><p></p>
<input type = "number" placeholder = "your weight" id = "weight" min = "1" max = "500"><p></p>
Your sex
<select name = "sex" id = "sex">
<option value = "1" id = "male">male</option>
<option value = "2" id = "female">female</select><p></p>
<button onclick="calculate()">Calculate</button>
</div>
<script>
var height = document.getElementById('height').onclick;
var age = document.getElementById('age').onclick;
var weight = document.getElementById('weight').onclick;
var sex = 1;
function calculate(height, age, weight, sex) {
switch(sex) {
case sex: 1
calculate = 66.5 * (13.75 * weight) + (5 * height) - (6.76 * age)
case sex: 2
calculate = 655.1 * (9.56 * weight) + (1.85 * height) - (4.68 * age)
break;
default: 1
}
document.getElementById('calculate').innerHTML = calculate
}
</script>
</body>
</html>

The error Uncaught TypeError: Cannot set property 'innerHTML' of null means that the object that you are calling .innerHTML on doesn't exist. In your case that's this line:
document.getElementById('calculate').innerHTML = calculate
and you get that error because you don't have an element with an id of calculate. If you don't have that element, you can't call .innerHTML on it.
You also need to get the data out of your form fields with the .value property, not the onclick property.
See additional comments below:
<html>
<head>
<title>Sample Page</title>
<style>
div { margin:1em; } /* adds vertical space before and after each div */
</style>
</head>
<body>
<div>
<!-- You can't have an <h2> if you don't already have an <h1> for it to be
a sub-section of. Don't use HTML elements because of how they style the output.
Use CSS to style. Also, don't use <p></p> to create vertical space. Again, use
CSS for style. -->
<h1> Daily calorie intake</h1>
<div><input type="number" placeholder="your height" id="height" min="1" max="230"></div>
<div><input type="number" placeholder="your age" id="age" min="1" max="120"></div>
<div><input type="number" placeholder="your weight" id="weight" min="1" max="500"></div>
<div>Your sex
<select id="sex">
<option value="1" id="male">male</option>
<option value="2" id="female">female</option>
</select>
</div>
<button>Calculate</button>
</div>
<div id="output"></div>
<script>
// Do your event binding in JavaScript, not in HTML
document.querySelector("button").addEventListener("click", calculate);
// Get references to the elements you'll need (not the value of their onclick properties)
var height = document.getElementById('height');
var age = document.getElementById('age');
var weight = document.getElementById('weight');
var sex = 1;
// You don't need any arguments because you already have references to the fields
// where the data is.
function calculate() {
// Declare the variable the will hold the result and don't use the
// name of the function as the name of the variable
let result = null;
switch(sex) {
// To get the data out of a form field, you must access its .value property
case sex: 1
result = 66.5 * (13.75 * weight.value) + (5 * height.value) - (6.76 * age.value);
break;
case sex: 2
result = 655.1 * (9.56 * weight.value) + (1.85 * height.value) - (4.68 * age.value);
break;
default: 1
}
// Make sure you reference elements that exist and don't use
// .innerHTML when there is no HTML in the string.
document.getElementById('output').textContent = result;
}
</script>
</body>
</html>

I hope this helps, this code is working
var height = document.getElementById('height');
var age = document.getElementById('age');
var weight = document.getElementById('weight');
var boton = document.getElementById('boton');
function calculate(height, age, weight, sex) {
switch(sex) {
case 1:
var calculo = 66.5 * (13.75 * weight) + (5 * height) - (6.76 * age);
break;
case 2:
var calculo = 655.1 * (9.56 * weight) + (1.85 * height) - (4.68 * age);
break;
default: 1
}
console.log(calculo);
return calculo;
}
boton.addEventListener('click', () => calculate(height.value, age.value, weight.value, 1));
<button id="boton"> Click me </button>
<input type = "number" placeholder = "your height" id = "height" min = "1" max = "230"/>
<input type = "number" placeholder = "your age" id = "age" min = "1" max = "120"/>
<input type = "number" placeholder = "your weight" id = "weight" min = "1" max = "500"/>

Related

I want user input to be calculated into Cylinder surface, volume and half of the surface areato then be printed into html

I've wanted to make a site to calculate different geometrical shapes as an side project, style it and possibly share it among my class, I got stuck on the first task for a few weeks now, THE CYLINDER
<!DOCTYPE html>
<html>
<head>
<title>Cylinder</title>
</head>
<body>
<form>
<!--takes input from user-->
<label for="Radius">Radius:</label>
<input type="number" id="r" name="Radius"><br><br>
<label for="Height">Height:</label>
<input type="number" id="v" name="Height"><br><br>
<button onclick="go();return false;">Script go!</button><br><br><br><br>
</form>
<div>
<!--will get replaced by result-->
<p id="x">S Povrch.</p> <!--Surface-->
<p id="y">V Obsah.</p> <!--Volume-->
<p id="z">Plovina S.</p> <!--Half of surface-->
<script>
function go() {
// fetches data value from input boxes
document.getElementById(r);
document.getElementById(v);
//declares user input into variables
var Ha = r;
var HaHa = v;
//calculates result
var Povrch = parseFloat(2 * 3.14 * Ha * (Ha + HaHa));
var Obsah = parseFloat(3.14 * Ha * Ha * HaHa);
var HalfS = parseFloat(2 * 3.14 * Ha * (Ha + HaHa) / 2);
//prints result
document.getElementById("x").innerHTML = "Povrch: " + Povrch;
document.getElementById("y").innerHTML = "Obsah: " + Obsah;
document.getElementById("z").innerHTML = "HalfS: " + HalfS;
}
</script>
</body>
</html>
When I run this in my browser, it returns NaN.
You've got a few typos in your JavaScript.
This:
document.getElementById(r);
document.getElementById(v);
is both invalid, and wouldn't do anything - you're selecting a few elements, but not storing those references (assuming the selectors were fixed) to anything. So, you want this:
var r = document.getElementById('r');
var v = document.getElementById('v');
Now you have a reference the elements with the IDs of 'r' and 'v'. Next, you need to read the value of those inputs, to get their... value:
var Ha = r.value;
var HaHa = v.value;
With those changes, your script yields output (I haven't verified that your math is correct, though), as noted in the Stack Snippet here:
function go() {
// fetches data value from input boxes
var r = document.getElementById('r');
var v = document.getElementById('v');
//declares user input into variables
var Ha = r.value;
var HaHa = v.value;
//calculates result
var Povrch = parseFloat(2 * 3.14 * Ha * (Ha + HaHa));
var Obsah = parseFloat(3.14 * Ha * Ha * HaHa);
var HalfS = parseFloat(2 * 3.14 * Ha * (Ha + HaHa) / 2);
//prints result
document.getElementById("x").innerHTML = "Povrch: " + Povrch;
document.getElementById("y").innerHTML = "Obsah: " + Obsah;
document.getElementById("z").innerHTML = "HalfS: " + HalfS;
}
<form>
<!--takes input from user-->
<label for="Radius">Radius:</label>
<input type="number" id="r" name="Radius"><br><br>
<label for="Height">Height:</label>
<input type="number" id="v" name="Height"><br><br>
<button onclick="go();return false;">Script go!</button><br><br><br><br>
</form>
<div>
<!--will get replaced by result-->
<p id="x">S Povrch.</p>
<!--Surface-->
<p id="y">V Obsah.</p>
<!--Volume-->
<p id="z">Plovina S.</p>
<!--Half of surface-->
</div>

Why does my function not fetch the value of variable?

The purpose of the code is to compute for the car market value. If If Age of the Car is :
1 - then subtract 20% from the Price of the Car
2 - then subtract 35% from the Price of the Car
3 - 7 - then subtract 35% from the Price of the Car and then subtract 10%
more for each year starting from the 3rd year.
8 - 10 - then the market value is fixed at 100,000.00
More than 10 years then the market value is fixed at 75,000.00.
Then it will display the name inputted and the value of the car but it doesnt seem to work. pls help
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
function calculateValue() {
switch (age) {
case 0:
price = price - 0.20 * price;
break;
case 1:
price = price - 0.35 * price;
break;
case 2:
price = price - 0.35 * price - (age - 3) * .10 * price;
break;
case 3:
price = 100000;
break;
case 4:
price = 75000;
break;
}
switch (condition) {
case 0:
price = price;
break;
case 1:
price = price - price * .10;
break;
}
document.getElementById("message").innerHTML = "Your" + name + " is valued at " + price + "today";
}
<h1>Car Market Value Calculator</h1>
<form>
Car Brand:<input id="name" type="text" name="name" placeholder="Please input car brand" autofocus required><br> Age of Car
<select id="age">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3-7</option>
<option value="3">8-10</option>
<option value="4">more than 10</option>
</select><br> Price of Car<input id="price" type="number" name="price" placeholder="minimum:300,000" min="300000"><br>
<p>Good Condition?</p>
Yes <input id="condition" type="radio" name="condition" value="0"> No <input id="condition" type="radio" name="condition" value="1">
<button type="button" name="submit" onclick="calculateValue()">Submit</button>
</form>
<p id="message"></p>
You have a few errors in your code:
You're not getting the input from the dom at the right moment. You should get the input values before calculation, not when the script loads. This ensures that the DOM is loaded, and get the right values.
The age value is not calculated properly. Don't use select for numeric values. Also, read again your case price = 2 ;)
This code does what you expect:
const calculateValue = () => {
let age = +document.querySelector('input[name=age]').value,
price = +document.querySelector('input[name=price]').value,
condition = document.querySelector('input[name=condition]').checked;
// depreciate based on age
if (age==1) price*=.8
else if (age==2) price*=.65
else if (age>2 && age<8) price*=(.65-(age-3)*.1)
else if (age>7 && age<11) price = 100000
else price = 75000;
// depreciate based on condition
if (!condition) price*=.9;
console.log(price);
}
<div>
<input name="age" type="number" placeholder="age">
</div>
<div>
<input name="price" type="number" placeholder="price">
</div>
<div>
Good condition?
<input name="condition" type="radio" value="true" checked>yes
<input name="condition" type="radio" value="false">no
</div>
<button onclick="calculateValue()">Compute</button>
If you open your browser's development console you'll see an error indicating that you're trying to get the .value of something that is null or undefined. Because document.getElementById("price") doesn't find anything when you're executing it.
You're trying to get the values of your inputs before the user has typed anything. Before the inputs have even been rendered on the page even.
You don't want to get the values until the user has pressed the button. So move that code into the function:
function calculateValue() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
//... the rest of your function
}
You need to move the first 6 lines where you are trying to get the values from input inside your calculateValue() function
function calculateValue() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
switch (age) {
...
Simply do this and your code will work fine.
Explanation: You need to get the new values from the input boxes each time the submit button is pressed. What you have done is that you have taken the values from the input boxes only once. As you move these lines inside the function, the fresh values are taken each time the button is pressed.
The document.getElementById commands will execute before the HTML markup is loaded, and hence will trigger an error. You can fix it by moving the variable declarations and value-fetching into the function:
function calculateValue() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
switch (age) {
case 0:
...etc...
You will want to do this anyway, since your code needs to fetch the current input values every time you click "submit".
Get values of your variables inside the calculate value function
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Car Market Value Calculator">
<meta name="keywords" content="calculator, car, market, value">
<meta name="author" content=", 26/02/19">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
</style>
</head>
<body>
<h1>Car Market Value Calculator</h1>
<form>
Car Brand:<input id="name" type="text" name="name" placeholder="Please input car brand" autofocus required><br>
Age of Car<select id="age">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3-7</option>
<option value="3">8-10</option>
<option value="4">more than 10</option>
</select><br>
Price of Car<input id="price" type="number" name="price" placeholder="minimum:300,000" min="300000" ><br>
<p>Good Condition?</p>
Yes <input id="condition" type="radio" name="condition" value="0">
No <input id="condition" type="radio" name="condition" value="1">
<button type="button" name="submit" onclick = "calculateValue()">Submit</button>
</form>
<p id="message"></p>
</body>
<script>
function calculateValue(){
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
alert(price);
switch (age) {
case 0:
price = price - 0.20*price;
break;
case 1:
price = price - 0.35*price;
break;
case 2:
price = price - 0.35*price - (age-3)*.10*price;
break;
case 3:
price = 100000;
break;
case 4:
price = 75000;
break;
}
switch(condition){
case 0:
price = price;
break;
case 1:
price = price- price*.10;
break;
}
document.getElementById("message").innerHTML = "Your"+ name +" is valued at "+price+"today";
}
</script>
</html>
Every time you click the submit you need to get the input values again, and not only when loading the page. Just move the 'var' declarations into the function:
function calculateValue() {
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var price = document.getElementById("price").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
switch (age) {
case 0:
price = price - 0.20 * price;
break;
case 1:
price = price - 0.35 * price;
break;
case 2:
price = price - 0.35 * price - (age - 3) * .10 * price;
break;
case 3:
price = 100000;
break;
case 4:
price = 75000;
break;
}
switch (condition) {
case 0:
price = price;
break;
case 1:
price = price - price * .10;
break;
}
document.getElementById("message").innerHTML = "Your" + name + " is valued at " + price + "today";
}
Solution at Codepen
function calculateValue() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
switch (age) {
case 0:
price = price - 0.20 * price;
break;
case 1:
price = price - 0.35 * price;
break;
case 2:
price = price - 0.35 * price - (age - 3) * .10 * price;
break;
case 3:
price = 100000;
break;
case 4:
price = 75000;
break;
}
switch (condition) {
case 0:
price = price;
break;
case 1:
price = price - price * .10;
break;
}
document.getElementById("message").innerHTML="Your"+name+" is valued at "+price+ "
today";
}`
The comments given by others are correct. You need to get the updated values on click of the submit button and hence all the variable will come inside the calculateValue function.
Wrap all the code in the document.ready method.

RealTime Calculations based on inputs and clicked radio buttons

I want to create a real time calculator for Net-Profit based on the trasaction, of the given quantity at given buy and sell price and it has 2 radio buttons as inputs.
What is happening is, I have to hit enter after putting values and selecting the button.
Where as what I want is, as soon as I input values and select radio button it should calculate the values.
Pl help me correct my code.
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Brokerage Calculator</title>
<head>
<script src="jquery-min.js"></script>
</head>
<body>
Buy Price
<input type="number" min="0" id="bp"><br />
Sell Price
<input type="number" min="0" id="sp"><br />
Qty:
<input type="number" min="0" id="qty"><br />
NSE:
<input name="exchname" id="nse" value="0.0000325" type="radio" checked="checked"><br />
BSE:
<input name="exchname" id="bse" value="0.0000275" type="radio"><br />
Turnover:
<span id="turnover">0</span><br />
Brokerage:
<span id="brokerage">0</span><br />
Security Transction Tax:
<span id="stt">0</span><br />
Total Tran Charges:
<span id="ttc">0</span><br />
SEBI Charges:
<span id="sebi">0</span><br />
Service Tax:
<span id="servtax">0</span><br />
Stamp Duty:
<span id="std">0</span><br />
Total Brokerage + Taxes:
<span id="ttx">0</span><br />
Net Profit:
<span id="pnl">0</span><br />
<script>
$('input').keyup(function(){ // run anytime the value changes
var buyPrice = parseFloat($('#bp').val()); // get value of field
var sellPrice = parseFloat($('#sp').val()); // convert it to a float
var quantity = parseFloat($('#qty').val());
var turnoverValue = (buyPrice + sellPrice) * quantity;
var sttValue = sellPrice * quantity * 0.025 / 100;
var sebiValue = turnoverValue * 0.0002 / 100;
var stdValue = 0.00002 * turnoverValue;
var excrate = document.querySelector('input[name="exchname"]:checked').value;
if(buyPrice<166.67){
var brkgbp = 0.05;
} else {
var brkgbp = buyPrice * 0.03 / 100;
}
if(sellPrice<166.67){
var brkgsp = 0.05;
} else {
var brkgsp = sellPrice * 0.03 / 100;
}
var brokerageValue = (brkgbp + brkgsp) * quantity;
var ttcValue = excrate * turnoverValue;
var servtaxValue = (brokerageValue + ttcValue + sebiValue) * 15 / 100;
var ttxValue = brokerageValue + sttValue + ttcValue + sebiValue + servtaxValue + stdValue;
var pnlValue = ((sellPrice - buyPrice) * quantity) - ttxValue;
$('#turnover').html(turnoverValue.toFixed(2));
$('#brokerage').html(brokerageValue.toFixed(2));
$('#stt').html(sttValue.toFixed(2));
$('#sebi').html(sebiValue.toFixed(2));
$('#servtax').html(servtaxValue.toFixed(2));
$('#ttc').html(ttcValue.toFixed(2));
$('#std').html(stdValue.toFixed(2));
$('#ttx').html(ttxValue.toFixed(2));
$('#pnl').html(pnlValue.toFixed(2));
});
<script>
</body>
</html>
Your closing script tag is missing the /, i.e. </script>
For your inputs, you're checking for the release of a keyboard key, which wouldn't fire for clicking radio buttons. Since you're checking to see if the value of the input has changed, you should change $('input').keyup to $('input').change.
edit: of course, you should do the NaN checking as well, as the other answers indicated - but the problem you described is solved by using the change event.
Didn't you forgot to close the script tag?
<script> ... </script>
Also, use
var buyPrice = parseFloat($('#bp').val()) || 0;
to initialize with a default value, so you don't get NaN
If you want the values to change when you reselect an option in the radio buttons, use:
function calculate(){ // run anytime the value changes
....
}
$('input').on('keyup', calculate);
$('input').on('click', calculate);
EDIT: I made a JSfiddle
https://jsfiddle.net/v3qd7b26/
Multiple issue in your code
1. You are missing the / in the script tag at the end. It should be </script> instead of <script>.
2. You need to ensure that the values entered are valid numbers only and then only proceed further, you can validate that using isNaN function in javascript
if(!isNaN(buyPrice) && !isNaN(sellPrice) && !isNaN(quantity)){
3.
Also, for checkbox need to add another selector. So you can create a common function and call it.
$("input").keyup(calculate);
$("input:checked").keyup(calculate);
Complete code:
$("input").keyup(calculate);
$("input:checked").keyup(calculate);
function calculate(){ // run anytime the value changes
var buyPrice = parseFloat($('#bp').val()); // get value of field
var sellPrice = parseFloat($('#sp').val()); // convert it to a float
var quantity = parseFloat($('#qty').val());
if(!isNaN(buyPrice) && !isNaN(sellPrice) && !isNaN(quantity)){
var turnoverValue = (buyPrice + sellPrice) * quantity;
var sttValue = sellPrice * quantity * 0.025 / 100;
var sebiValue = turnoverValue * 0.0002 / 100;
var stdValue = 0.00002 * turnoverValue;
var excrate = document.querySelector('input[name="exchname"]:checked').value;
if(buyPrice<166.67){
var brkgbp = 0.05;
} else {
var brkgbp = buyPrice * 0.03 / 100;
}
if(sellPrice<166.67){
var brkgsp = 0.05;
} else {
var brkgsp = sellPrice * 0.03 / 100;
}
var brokerageValue = (brkgbp + brkgsp) * quantity;
var ttcValue = excrate * turnoverValue;
var servtaxValue = (brokerageValue + ttcValue + sebiValue) * 15 / 100;
var ttxValue = brokerageValue + sttValue + ttcValue + sebiValue + servtaxValue + stdValue;
var pnlValue = ((sellPrice - buyPrice) * quantity) - ttxValue;
$('#turnover').html(turnoverValue.toFixed(2));
$('#brokerage').html(brokerageValue.toFixed(2));
$('#stt').html(sttValue.toFixed(2));
$('#sebi').html(sebiValue.toFixed(2));
$('#servtax').html(servtaxValue.toFixed(2));
$('#ttc').html(ttcValue.toFixed(2));
$('#std').html(stdValue.toFixed(2));
$('#ttx').html(ttxValue.toFixed(2));
$('#pnl').html(pnlValue.toFixed(2));
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Buy Price
<input type="number" min="0" id="bp"><br />
Sell Price
<input type="number" min="0" id="sp"><br />
Qty:
<input type="number" min="0" id="qty"><br />
NSE:
<input name="exchname" id="nse" value="0.0000325" type="radio" checked="checked"><br />
BSE:
<input name="exchname" id="bse" value="0.0000275" type="radio"><br />
Turnover:
<span id="turnover">0</span><br />
Brokerage:
<span id="brokerage">0</span><br />
Security Transction Tax:
<span id="stt">0</span><br />
Total Tran Charges:
<span id="ttc">0</span><br />
SEBI Charges:
<span id="sebi">0</span><br />
Service Tax:
<span id="servtax">0</span><br />
Stamp Duty:
<span id="std">0</span><br />
Total Brokerage + Taxes:
<span id="ttx">0</span><br />
Net Profit:
<span id="pnl">0</span><br />

Celsius and Fahrenheit Converter- JavaScript

I want to make a webpage that has two text boxes, a Celsius and Fahrenheit box. In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!" So far, I haven't figured out how to get the alert and when I type numbers in the Celsius box, it always says the number -18 in the same box. Fahrenheit is fine.
HTML:
<html>
<head>
<title>Temparature Converter</title>
<script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
Celsius: <input id="c" onkeyup="convert('C')">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>
JavaScript:
function convertTemp(degree) {
if (degree == "C") {
F = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(F);
} else {
C = (document.getElementById("f").value -32) * 5 / 9;
document.getElementById("c").value = Math.round(C);
}
}
Note: I got some code from W3Schools so I think the onkeyup convert is a little funny. If possible, please notify me how it has to change as well as the JavaScript.
There is no need for the onkeyup attributes, since they original code from W3Schools was designed to instantly update values as they were entered.
I did modify the functionality to clear of original value, that way the conversion button can work both ways with a simple code.
Here's a quick JavaScript to do the job:
function convertTemp() {
// Set the initial variables for c (Celsius) and f (Fahrenheit)
var c = document.getElementById('c'), f = document.getElementById('f');
// Test if there is a value for Celsius
if(c.value != '') {
// Set the value for Fahrenheit
f.value = Math.round(c.value * 9 / 5 + 32);
// Clear the value for Celsius
c.value = '';
// If there isn't a value for Celsius
} else {
// Set the value for Celsius
c.value = Math.round((f.value - 32) * 5 / 9);
// Clear the value for Fahrenheit
f.value = '';
}
}
And its accompanying HTML:
Celcius:<input id="c">
Fahrenheit:<input id="f">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
It can be tested at: http://jsfiddle.net/bhz6uz54/
Something to remember about simple code, like this, there is nothing to verify the supplied values are acceptable. A little regex can act as validation, but how it would be implemented depends on how you want to flag the problem.
I personally hate Do-it Buttons so I'd go with a more dynamic solution:
// Get the Input elements:
var $f = document.getElementById("f");
var $c = document.getElementById("c");
function FC_CF() {
var temp; // Will hold the temperature value
var $targ; // Used to target the element we're not typing into:
if (this.id === "c") { // If we're typing into #c...
$targ = $f; // use #f as target element
temp = (this.value * 9 / 5) + 32; // C2F
} else {
$targ = $c;
temp = (this.value - 32) * 5 / 9; // F2C
}
// Write the result "as we type" in the other ($targ) field:
$targ.value = !isNaN(temp) ? parseFloat(temp.toFixed(1)) : "Err";
// (Above:) temp is a num ? return floated number, else: "Show some error"
}
// Assign input listeners to trigger the above function:
$f.oninput = FC_CF;
$c.oninput = FC_CF;
Celcius: <input id="c">
Fahrenheit: <input id="f">
You can separate the functions which do the temperature conversion as follows i did somw changes in the code.
<p>
<label>Fahrenheit</label>
<input id="outputFahrenheit" type="number" placeholder="Fahrenheit"
oninput="temperatureConverterCelsius(this.value)"
onchange="temperatureConverterCelsius(this.value)" value="">
</p>
<p>Celsius: </p>
<input id="outputCelsius" type="number" placeholder="Celsius"
oninput="temperatureConverterFahrenheit(this.value)"
onchange="temperatureConverterFahrenheit(this.value)" value="">
</p>
<script type=""text/javascript>
function temperatureConverterCelsius(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelsius").value = (valNum-32) / 1.8;
//document.getElementById("outputFahrenheit").value = (valNum*1.8)+32;
}
</script>
</body>
</html>
class Temperature_conversation {
constructor(celsius) {
this.celsius= celsius;
this.fahrenheit= 0;
this.table_begin= -50.0;
this.table_end= 50.0;
this.table_step= 10.0;
console.log('---------------------Conversion--------------------------');
console.log('Celsius fahrenheit');
for(this.celsius = this.table_begin; this.celsius <= this.table_end; this.celsius += this.table_step){
this.fahrenheit = this.celsiusToFahrenhit(celsius);
}
}
celsiusToFahrenhit(c){
const minimun_celsius = -273.15;
if (c < minimun_celsius) {
throw 'O argumento es pequeno';
}
this.celsius = (9.0 / 5.0) * c+ 32;
var res = [this.celsius, this.fahrenheit]
console.table(res);
}
}

What's wrong with this code? I think I messed up in the communication between HTML and Javascript

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;

Categories