Paxana Non Grata
Paxana Non Grata

Reputation: 389

my javascript checkbox doesn't do anything

http://codepen.io/PaxBlueRibbon/pen/wWJWXj

I'm trying to teach myself Javascript, but this fahrenheit/celsius switch doesn't do anything. I set up my switch like this:

$(document).ready(function getPosition() {
  if (document.getElementById('myonoffswitch').checked) {
    var unit = "Fahrenheit";
  } else {
    var unit = "Celsius";
  }

and set conditionals in the JS like this

      var tempKelvin = json.main.temp;
      var tempFahrenheit = tempKelvin * 1.8 - 459.67;
      var tempCelsius = tempKelvin - 273.15;
      if (unit == "Fahrenheit") {
        $(".temp").html(Math.round(tempFahrenheit) + " Degrees " + unit);
      }
      if (unit == "Celsius") {
$(".temp").html(Math.round(tempCelsius) + " Degrees " + unit);
      }

The fahrenheit works, and if I change the variable to something else it stops working, but I can't get it to show Celsius.

Upvotes: 0

Views: 61

Answers (1)

exabyssus
exabyssus

Reputation: 451

Since you are using jQuery.

// you should add event listener.
$('#myonoffswitch').change(function(){
    // and change "unit" every time checkbox is changed
    unit = $(this).prop('checked') ? 'Fahrenheit' : 'Celsius';
    // change html here
});

And you can call this event on page load

$('#myonoffswitch').change();

Upvotes: 1

Related Questions