Factors are integers that divide a number evenly with remainder 0. The factors of 12 are 1, 2, 3, 4, 6, 12.
The original exercise omitted 1 and the number itself from its output even though its definition included them. This corrected version displays the complete factor set.
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>JavaScript Factors Demo</title></head>
<body>
<label for="t1">Enter a positive integer</label>
<div class="col-sm-4 px-0"><input type="number" class="form-control" id="t1" min="1" max="1000000" step="1"></div>
<button type="button" class="btn btn-primary btn-sm mt-2" id="b1">Submit</button>
<div id="d1" class="alert alert-success mt-3" aria-live="polite">Output here</div>
<script>
const input = document.getElementById("t1");
const output = document.getElementById("d1");
const submitButton = document.getElementById("b1");
function showFactors() {
const number = Number(input.value.trim());
if (!Number.isInteger(number) || number < 1 || number > 1000000) {
output.textContent = "Enter a positive integer from 1 to 1,000,000.";
return;
}
const factors = [];
for (let i = 1; i <= number; i += 1) {
if (number % i === 0) {
factors.push(i);
}
}
output.textContent = `Factors are: ${factors.join(", ")}`;
}
submitButton.addEventListener("click", showFactors);
</script>
</body>
</html>
The remainder operator % is used to test divisibility. If number % i === 0, then i is a factor. This straightforward loop is intentionally easy to follow for an exercise page.
| Number.isInteger() | Check whether a parsed value is an integer. |
| parseInt() | Convert a string to an integer where that conversion is appropriate. |
Next lower value of any decimal number JavaScript Basic JavaScript variable
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.