Skip to content

Instantly share code, notes, and snippets.

@Karlina-Bytes
Created October 28, 2014 04:50
Show Gist options
  • Save Karlina-Bytes/dfd515f48cd8590840ed to your computer and use it in GitHub Desktop.
Save Karlina-Bytes/dfd515f48cd8590840ed to your computer and use it in GitHub Desktop.
A JavaScript function for handling the "button click" in a base converter calculator.
/*********************************************************
* Responds to the "Convert!" button click.
* (This could be thought of as the "main" function).
*
* INPUT: Validate the web form input.
* PROCESSING: Perform the conversions.
* OUTPUT: Display the results on the web page.
********************************************************/
function buttonClick() {
// 1) Extract user data from the form fields.
var inputNumber = document.getElementById("startField").value;
var inputBase = document.getElementById("startBaseSelect").value;
var outputBase = document.getElementById("endBaseSelect").value;
// 2) Remove spaces and set letters to uppercase.
inputNumber = sanitizeInput(inputNumber);
// 3.1) If inputNumber and inputBase don't match, flag an error.
if (!numberAndBaseMatch(inputNumber, inputBase))
displayResult(
"Error: Invalid number. <br>" +
"Please enter a positive base-" +
inputBase + " integer.<br>"
);
// 3.2) Otherwise, proceed with the base conversion.
else {
// 3.2.1) Convert the inputNumber to the given outputBase.
inputBase = parseInt(inputBase);
outputBase = parseInt(outputBase);
var outputNumber = baseConvert(inputNumber,inputBase,outputBase);
// 3.2.2) Display the result on the web page.
displayResult(
inputNumber + " (base " + inputBase + ") = " +
outputNumber + " (base " + outputBase + ")"
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment