Weather App - Change Text in Button

Hello!

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;
}
}

I couldn’t post the HTML here for some reason :frowning:

You can find the full code here: http://codepen.io/ellereeeee/pen/OREyEq?editors=1010

I’ve spent several hours looking for and trying answers from Google but haven’t had any luck.
I appreciate any help!

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
      })

Change button text could be written like this:

      $('#temp').click(function() {
        tempIsF ? $('#temp').html(tempC) : $('#temp').html(tempF)
        tempIsF = !tempIsF
      })
1 Like

You are using comparison (==) operator instead of assignment operator (=) in if and else too - el.innerHTML == tempF;.

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;
      }

result here : http://codepen.io/Hallucinogen/pen/QKJzqz

Thanks a lot for helping guys! I hadn’t thought of using a Boolean in this situation and it’s pretty eye-opening to see what you guys suggested.

Thanks, your reply is really elegant! I hope it’s ok if added it to my code.

I didn’t know about ternary conditionals and the logical not operator :slight_smile: