I want to switch text in a button when I click on it. The weather in degrees is a button, and if it’s in Celsius I want to switch to Fahrenheit when pressed and vice versa.
Here’s the relevant JS:
function change() {
var el = document.getElementById(“temp”)
if (el.innerHTML == tempC) {
el.innerHTML == tempF;
}
else {
el.innerHTML == tempC;
}
}
One possible solution (remember to remove onclick="change()" from button in HTML):
var tempIsF = true; // <-- added variable to store current temp value
if (weatherData.sys.country === 'US') {
$('#temp').html(tempF);
} else {
$('#temp').html(tempC);
tempIsF = false; // <-- as temp is in C set it to false
}
//change button text
$('#temp').click(function() {
if (tempIsF) {
$('#temp').html(tempC);
} else {
$('#temp').html(tempF);
}
tempIsF = !tempIsF
})
I forked your app and modified this part of the code :
// first of all, delete onclick="change()" in html code
var isFahrenheit; // true or false
if (weatherData.sys.country === 'US') {
isFahrenheit = true;
$('#temp').html(tempF);
}
else {
isFahrenheit = false;
$('#temp').html(tempC);
}
//change button text
$("#temp").on('click', change);
function change() {
isFahrenheit = !isFahrenheit; // we flip the value of isFahrenheit, if it's true, become true and vice versa
var el = document.getElementById("temp")
el.innerHTML = isFahrenheit ? tempF : tempC;
}