The Code
// step 1: get the start and end numbers from the input boxes
function getValues() {
// get the inputs by their ID
let startValue = document.getElementById('startValue').value;
let endValue = document.getElementById('endValue').value;
startValue = parseInt(startValue);
endValue = parseInt(endValue);
if (isNaN(startValue) || isNaN(endValue)){
Swal.fire({
icon: 'error',
title: 'Uh oh!',
text: 'Please enter a valid number for both the start and end values.',
backdrop: false
});
}
else if (startValue >= endValue) {
Swal.fire({
icon: 'error',
title: 'Uh oh!',
text: 'Please enter a valid number for both the start and end values.',
backdrop: false
});
}
else {
let values = generateNumbers(startValue, endValue);
displayNumbers(values);
}
}
// step 2: get all the numbers in that range
function generateNumbers(start, end) {
let numbers = [];
for (let number = start; number <= end; number = number + 1) {
numbers.push(number);
}
return numbers;
}
// step 3: put those numbers on the page
function displayNumbers(values) {
let resultsTable = document.getElementById('result');
resultsTable.innerHTML = '';
// for each number in values:
for (let i = 0; i < values.length; i = i + 1) {
// - create some HTML with the number
let number = values[i];
let html = '<tr><td>'
// - determine whether it should be bold
if (number % 2 == 0) {
html += '<b>' + number + '</b>';
}
else {
html += number;
}
html += '</td></tr>';
// - put it on the page in the element with the ID result
resultsTable.innerHTML += html;
}
}
>
The code is structured in 3 functions.
getValues()
The getValues()
function gets the start and end values entered by the user,
making sure they're numbers. It checks if the inputs are valid numbers, and if not,
it shows an error message using SweetAlert. Also, it checks that the start value is less
than the end value; if not, it shows the same error message. If everything is okay,
it then makes a list of numbers from the start to the end.
generateNumbers()
The generateNumbers()
function creates an array of numbers within a specified range.
The function uses a for loop to go through each number from 'start' to 'end', increasing by 1 each time.
In every step, the function adds the current number to the 'numbers' list.
After finishing all the steps, it gives back the list containing the numbers from 'start' to 'end.'
So, it's a way to create a list of numbers within a specific range.
displayNumbers()
The displayNumbers()
function shows a list of numbers on a webpage.
It checks if each number is even, making those bold. After doing this for all numbers,
it displays them on the webpage in a table with the ID 'result'.