Troubleshooting the use of if/else inside a event function - javascript

I am having trouble using an if else to achieve a simple two-way celsius/fahrenheit conversion using basic HTML input fields and some background Javascript.
Basically, I want to be able to enter a value in C or F into one of the two inputs and then have the conversion appear in the other input. The Celsius to Fahrenheit conversion works OK, but nothing happens when entering numbers into the Fahrenheit input. My code is below
var celsius = document.getElementById("Celsius");
var fahrenheit = document.getElementById("Fahrenheit");
celsius.addEventListener('input', conversion);
fahrenheit.addEventListener('input', conversion);
function conversion() {
var celsiusvalue = document.getElementById("Celsius").value;
var fahrenheitvalue = document.getElementById("Fahrenheit").value;
const intcelsius = parseInt(celsiusvalue, 10);
const intfahrenheit = parseInt(fahrenheitvalue, 10);
if (this.id == "Celsius") {
fahrenheit.value = ((intcelsius * 9)/5) + 32;
}
else {
celsius.value == (((intfahrenheit - 32) * 5) / 9);
}
}
<section>
<input id="Celsius" placeholder="Celsius"/><br/><br/>
<input id="Fahrenheit" placeholder="Fahrenheit"/>
</section>
Can anyone help me out? Should I not be using if/else here and just use two different functions?

celsius.value == (((intfahrenheit - 32) * 5) / 9);
should be:
celsius.value = (((intfahrenheit - 32) * 5) / 9);

Related

How can I declare a variable to solve this in my temperature calculator?

I am currently trying to write code in Visual Studio Code to convert Celsius to Fahrenheit, and I have my prompts to ask the user what temperature they want to convert and which of the two they would like to convert.
I am stuck on how to declare the variable that displays the solution to my conversion formula. Here is what I have so far.
let userInput = prompt("would you like to convert to C or F?")
let userTemp = prompt("what temperature?")
console.log("30" == 30)
console.log(30 === 30)
console.log("" == 0)
toLower(c)
toLower(f)
let result = (userInput / 5 * 9) + 32
if (userInput == 'c') {
(userTemp / 5 * 9) + 32 == result // <- Needs to ba a variable before you use it
}
else {
(userTemp - 32) * 5 / 9 == result
}
document.write(result)
There are a few things wrong with your code. Although you do create a variable result, you're trying to convert a c or f to a number, you should be using userTemp here instead of userInput.
This is a moot point though as (userTemp / 5 * 9) + 32 == result is an equality check and results in a boolean (true/false) value.
You should instead assign (userTemp / 5 * 9) + 32 to the variable result
result = (userTemp / 5 * 9) + 32;
So you need to not assign a value initially to result and assign the value inside the if ... else.
let userInput = prompt("would you like to convert to c or f?")
let userTemp = prompt("what temperature?")
userInput = userInput.toLowerCase();
let result;
if (userInput == 'c') {
result = (userTemp - 32) * 5 / 9
} else {
result = (userTemp * 9 / 5) + 32
}
document.write(result)
I've also swapped the calculations as converting 61 to c gave 141.8 instead of 16.1.

Why isn't this converting correctly?

This is suppose to return the converted number as a whole number. That part works but it doesn't turn the right conversion.
var input = prompt('Please enter your temp in fahrenheit');
function converter (){
var x = Math.round(input - 32 * 5/9);
console.log(x);
return x;
}
alert('The temp in celsius is: ' + converter());
The equation to convert Fahrenheit to Celcius is T(°C) = (°F - 32) × 5/9. You run into an order of operations issue. This should work.
var input = prompt('Please enter your temp in fahrenheit');
function converter (){
var x = Math.round((input - 32) * 5/9);
console.log(x);
return x;
}
alert('The temp in celsius is: ' + converter());
You are missing the paranthesis , which forced the operator precedence to take over the calculation.
var input = prompt('Please enter your temp in fahrenheit');
function converter() {
var x = Math.round((input - 32) * 5 / 9);
console.log(x);
return x;
}
alert('The temp in celsius is: ' + converter());
Try with this:
(input - 32) * (5 / 9);
That isn't correctly converting because of operator precedence, JavaScript operator precedence goes from highest (20) to lowest (0), Multiplication/Division has a precedence of 14 and Subtraction has a precedence of 13, so parenthesis (precedence 20) is required to mark which expression should execute first.
$(document).ready(function () {
$('#celsius').on('input', function (event) {
var celsius = $('#celsius').val();
var fahrenheit = celsiusToFahrenheit(celsius);
$('#fahrenheit').val(fahrenheit);
});
$('#fahrenheit').on('input', function (event) {
var fahrenheit = $('#fahrenheit').val();
var celsius = fahrenheitToCelsius(fahrenheit);
$('#celsius').val(celsius);
});
function celsiusToFahrenheit(celsius) {
if (celsius === undefined || celsius === null) {
return celsius;
}
var fahrenheit = celsius * 9/5 + 32;
return fahrenheit.toFixed(5);
}
function fahrenheitToCelsius(fahrenheit) {
if (fahrenheit === undefined || fahrenheit === null) {
return fahrenheit;
}
var celsius = (fahrenheit - 32) * 5/9;
return celsius.toFixed(5);
}
});
.form-group {
float: left;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form-group">
<label>Celsius</label>
<input type="text" id="celsius"/>
</div>
<div class="form-group">
<label>Fahrenheit</label>
<input type="text" id="fahrenheit"/>
</div>

Javascript populating hidden fields on mouseover - Before click

Looking for a solution to another problem I cam across the ability to run javascript on mouseover
I'd like to run this:
$(document).ready(function(){
function myPayment()
{
var value = document.mortgagecalc.value_input.value;
var rate = document.mortgagecalc.rate_input.value;
var term = document.mortgagecalc.term_input.value;
var deposit = document.mortgagecalc.deposit_input.value;
var fee = document.mortgagecalc.fee_input.value;
var totalloan = ((value + fee) - deposit) * 1 + rate;
var totalinterest = (totalloan * 1 + rate) - totalloan;
var months = (term * 12);
var repay = totalloan / months;
var interest = totalinterest / months;
// Calculate mortgage payment and display result
document.getElementById('repay_input').value = repay;
document.getElementById('interest_input').value = interest;
}
}
When a user mouses over my submit button
When the script runs I'd like it to populate these fields which are then included in the form action
<input type="hidden" name="repay" id="repay_input" value="">
<input type="hidden" name="interest" id="interest_input" value="">
Right now it doesn't seem to work but this may be because I've missed a small thing or it just won't work entirely
Thank you - If anyone has a better idea on how to achieve my aim please let me know, I've tried PHP but no joy
Button for clarity
<button class="col-sm-4 enter-button" type="submit" name="submit" onmouseover="return myPayment()" value="Calculate">Calculate Payments</button>
Update:
I tweaked the javascript and the button but then missed off naming the form to match the reference in the JS
Also my mortgage calculations were WAY off due to the way the form collects % rate
Declare your function outside of jQuery's document.ready wrapper, and your button only needs to look like this:
function myPayment()
{
var value = document.mortgagecalc.value_input.value;
var rate = document.mortgagecalc.rate_input.value;
var term = document.mortgagecalc.term_input.value;
var deposit = document.mortgagecalc.deposit_input.value;
var fee = document.mortgagecalc.fee_input.value;
var totalloan = ((value + fee) - deposit) * 1 + rate;
var totalinterest = (totalloan * 1 + rate) - totalloan;
var months = (term * 12);
var repay = totalloan / months;
var interest = totalinterest / months;
// Calculate mortgage payment and display result
document.getElementById('repay_input').value = repay;
document.getElementById('interest_input').value = interest;
}
<button onmouseover="myPayment()" ...></button>

Limiting the Value of an input in JavaScript function

I'm creating the following web app for my employer:
https://jsfiddle.net/kupe2rLL/3/
How it Works: The Missed Opportunity and Engage Results fields populate dynamically as users enter information in the Company Info section.
The Problem: I need to program the app so that the Years in Business input takes no value less than 1 and no value greater than three when calculating the jobsRecovered variable and RevenueYear variable only.
<input type="text" id="yearsOpen" name="yearsOpen" class="form-control" onchange="calculateAll()" required>
var jobsRecovered = (averageJobs * 50) * recovery * yearsOpen;
var revenueYear = jobsRecovered * jobValue;
Preferably, I need the Years in Business input field to accept any value from 0 to infinity on the form input but then change the value of that variable to a minimum of 1 and maximum of 3 when making calculations for the jobsRecovered variable and RevenueYear only. I'd like to implement this solution using a JavaScript function if possible but I am open to alternate solutions.
I researched and implemented the following solution but unfortunately this only limits the min - max range of input on the form itself:
input.addEventListener('change', function(e) {
var num = parseInt(this.value, 10),
min = 1,
max = 3;
if (isNaN(num)) {
this.value = "";
return;
}
this.value = Math.max(num, min);
this.value = Math.min(num, max);
});
Any assistance would be appreciated. (Note: My experience with programming is Beginner level.)
To limit the range of the variable value, you can pass it through if-else statements, or a ternary operation which act like a filter for your values.
e.g.
if (yearsOpen <= 3) ? (if (yearsOpen < 1) ? (yearsOpen = 1) : (yearsOpen = yearsOpen)) : (yearsOpen = 3);
smaller statement if (n <= 3) ? (if (n < 1) ? (n = 1) : (n = n)) : (n = 3);
If-else format:
if (yearsOpen <= 3) {
if (yearsOpen < 1) {
yearsOpen = 1;
} else {
yearsOpen = yearsOpen;
}
} else {
yearsOpen = 3;
}
Hope that makes sense.

Temperature Converter (IF ELSE conditions) in JavaScript

I am creating a Temperature Converter out of JavaScript. So far only the Celsius conversion works when the user inputs that first. I am just having trouble figuring out how to structure the other if statements.
var conversionC;
var conversionF;
var conversionK;
if ( celsius.value != "" ) {
conversionF = document.getElementById("celsius").value * 9 / 5 + 32;
document.getElementById("fahrenheit").value = Math.round(conversionF);
}
else if ( fahrenheit.value != "" ){
conversionC = (document.getElementById("fahrenheit").value - 32) * 5 / 9;
document.getElementById("celsius").value = Math.round(conversionC);
}
if ( kelvin.value != "" ){
conversionC = document.getElementById("celsius").value - -273;
document.getElementById("kelvin").value = Math.round(conversionC);
}
I only want to keep the one Convert button that I have, and still have it work when the user decides to input a Fahrenheit or Kelvin first.
Any guidance is greatly appreciated!
Here is a JSFiddle of my program so far:
https://jsfiddle.net/2sharkp/kw2sr1wx/
Thanks!
In your JSFiddle, you are taking each value and converting it into a float with parseFloat.
This means that when you hit if ( celsius.value != "" ), you are calling .value on a number, which is undefined. So you're really calling if ( undefined != "" ), which is true, and your first if block will always execute.
I'm assuming that your intention is to take the most recently edited field and use that for the conversion. I would recommend using a flag to indicate which field was last edited.
https://jsfiddle.net/camEdwards/chyg4ws1/
<script>
let cels = document.getElementById('cels');
let fahr = document.getElementById('fahr');
cels.addEventListener('input', function(){
let f = (this.value * 9/5) +32;
if(!Number.isInteger){
return f.toFixed(2);
}
fahr.value = f;
});
fahr.addEventListener('input', function(){
let c = (this.value - 32) * 5/9;
if(!Number.isInteger){
return c.toFixed(2);
}
cels.value = c;
});
</script>

Categories