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 either from kilograms to pounds or from pounds to killograms depending on the dropdown box.

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. A runnable version of the solution is here. (Don't peek at the solution code!)

Exercise Solution

Solution conversions.html, and conversions.js:

function convert() {
   var input = document.getElementById("input");
   value = parseInt(input.value);
   
   var conversion = document.getElementById("convert");
   if (conversion.value == "kgtopounds") {
      value *= 2.20462262;
   } else {
      value *= 0.45359237;
   }
   
   var answer = document.getElementById("answer");
   answer.innerHTML = value;
}