The Code
function getValues() {
// Take user inputs and set them to variables for later use
let startValue = document.getElementById("startValue").value;
let endValue = document.getElementById("endValue").value;
// Convert user inputs to an interger
startValue = parseInt(startValue);
endValue = parseInt(endValue);
// Check if the user input are valid numbers
if(Number.isInteger(startValue) && Number.isInteger(endValue)){
// If user input is valid generate numbers then display them
let numbers = generateNumbers(startValue, endValue);
displayNumbers(numbers);
} else {
// If user input isn't valid ask for proper input
alert("You must enter a number.");
}
}
function generateNumbers(start, end) {
// Build an array of the numbers
let numbers = [];
for(i = start; i <= end; i++){
// Loop through counting from the start
// value to the end value adding each one to the array
numbers.push(i);
}
// Give the array of numbers back to the calling function
return numbers;
}
function displayNumbers(numbers) {
// Build out the HTML to be displayed
let templateCols = "";
for(let i=0; i < numbers.length; i++) {
// Loop over the array
let classname = "";
if(numbers[i] % 2 == 0) {
// If the number is even then add the even class
let classname = "even";
// Add the new chunk to the current HTML
templateCols += `<div class="col ${classname}">${numbers[i]},</div>`;
} else {
// If the number is odd then add the odd class
let classname = "odd";
// Add the new chunk to the current HTML
templateCols += `<div class="col ${classname}">${numbers[i]},</div>`;
}
}
// Set the HTML element to contain the output
document.getElementById("outputData").innerHTML = templateCols;
}
getValues
This function takes the user input, assigns each field to a variable. We convert the user input to intergers, and validate them. Then uses those variables to call the next functions.
generateNumbers
Here we use loop to count from the starting value to the end value. Every loop we push the loop number to a new array that we then pass back to the calling function.
displayNumbers
In this function we build out the HTML to be shown to the user. We start loop over the array once, wrapping each element in HTML, adding an odd or even class based on the number. Each time we loop over it we add the new Div to the string that we will then display to the user.