Exercise : Weight Conversion

Create the file conversions.js referenced by conversions.html. Write a function convert() in conversions.js that takes the value in the text input and converts it from the unit selected in the left dropdown box to the unit selected on the right.

The result should be displayed in the empty span with the id of #answer.

The conversion factor from pounds to kilograms is 0.45359237, and the conversion factor from kilograms to pounds is 2.20462262.

You should edit the HTML file conversions.html to add ids to the elements as necessary and you may assume valid input.

Exercise Solution

Solution conversions.html, and conversions.js:

function convert() {
   var input = document.getElementById("input");
   value = parseInt(input.value);
   
   var from = document.getElementById("from");
   var to = document.getElementById("to");
   if (from.value == "kg" && to.value == "lb") {
      value *= 2.20462262;
   } else if (from.value == "lb" && to.value == "kg") {
      value *= 0.45359237;
   }
   
   var answer = document.getElementById("answer");
   answer.innerHTML = value;
}