my javascript checkbox doesn't do anything

时间:2016-07-11 21:07:50

标签: javascript jquery checkbox

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.

1 个答案:

答案 0 :(得分:1)

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();