Factors of an Input Number in JavaScript

Table of Contents

What Are Factors? Top ↑

Factors are integers that divide a number evenly with remainder 0. The factors of 12 are 1, 2, 3, 4, 6, 12.

Find the Factors of a Number Top ↑

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.

Output here

Complete Working Source Top ↑

<!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>

How the Divisibility Test Works Top ↑

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

JavaScript Math Reference




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer