Skip to content

Instantly share code, notes, and snippets.

@johnathanDOS
Created June 5, 2017 00:17
Show Gist options
  • Save johnathanDOS/355c3476441d02d045f39004a4c195af to your computer and use it in GitHub Desktop.
Save johnathanDOS/355c3476441d02d045f39004a4c195af to your computer and use it in GitHub Desktop.
This function interacts with HTML elements to convert a number from one unit of measurement to another.
function convertUnit() {
//check to see if the input is a number
var input = document.getElementById("userInput").value
var startUnit = document.getElementsByName("startUnit");
var endUnit = document.getElementsByName("endUnit");
var output = ""
//check to see if input is a number
if (isNaN(input) == true) {
alert("Please input a valid number");
}
//check to make sure all of the radio buttons are checked
if (startUnit[0].checked == false && startUnit[1].checked == false) {
alert("Please select the unit you are converting from");
}
if (endUnit[0].checked == false && endUnit[1].checked == false) {
alert("Please select the unit you are converting to");
}
//check to see if the start unit is grams
if (startUnit[0].checked == true) {
console.log("start at grams");
//check to see if the end unit is grams
if (endUnit[0].checked == true) {
//convert grams to grams - take no action
output = (input + " grams = " + input + " grams ")
console.log("end at grams");
}
//check to see if the end unit is pounds
if (endUnit[1].checked == true) {
//convert grams to pounds - multiply input by 0.00220462262185
var conversion = input * 0.00220462262185
output = (input + " grams = " + conversion + " lb ")
console.log('end at pounds');
}
}
//check to see if the start unit is pounds
if (startUnit[1].checked == true) {
console.log("start at pounds");
//check to see if the end unit is pounds
if(endUnit[1].checked == true) {
//convert pounds to pounds - take no action
output = (input + " pounds = " + input + " pounds")
console.log("end at pounds")
}
//check to see if end unit is grams
if(endUnit[0].checked == true) {
//convert pounds to grams
conversion = input / 0.00220462262185
output = input + " pounds = " + conversion + " grams"
}
}
document.getElementById("output").innerHTML = output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment