A prime number is a natural number greater than 1 with exactly two positive factors: 1 and itself. Numbers less than 2, including 0, 1, and negative integers, are not prime.
The original input and Submit facility is retained. The logic is corrected so that 1 is not incorrectly reported as prime.
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>JavaScript Prime Number Check</title></head>
<body>
<label for="t1">Enter an integer</label>
<div class="col-sm-4 px-0"><input type="number" class="form-control" id="t1" 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 isPrime(number) {
if (number < 2) return false;
if (number === 2) return true;
if (number % 2 === 0) return false;
for (let divisor = 3; divisor <= Math.sqrt(number); divisor += 2) {
if (number % divisor === 0) return false;
}
return true;
}
function checkPrime() {
const number = Number(input.value.trim());
if (!Number.isInteger(number)) {
output.textContent = "Enter an integer.";
return;
}
output.textContent = isPrime(number)
? `${number} is a prime number.`
: `${number} is not a prime number.`;
}
submitButton.addEventListener("click", checkPrime);
</script>
</body>
</html>
If a composite number has a factor greater than its square root, it must also have a matching factor below the square root. Testing only up to Math.sqrt(number) therefore avoids unnecessary iterations.
| 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 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.