1

This code should detect where a number is above 1,000,000,000 and below 9,999,999,999. I try to input numbers between these 2 values, but it still returns the else statement. Where is the problem in this code?

<html>
<head>
<title>Checking with RegExp</title>
</head>
<body>
<p>Enter a 10 digit number between 1000000000 and 9999999999.</p>
<textarea id="inputnumber"></textarea>
<button type="button" id="submitnumber">Check</button>
<script>
function checknumber() {
var tendigitnum = document.getElementById("inputnumber")
if (tendigitnum >= 1000000000 && tendigitnum <= 9999999999) {
alert("You entered the number" + tendigitnum + ".")
}
else {
alert("The page will refresh. Please enter a valid number.")
location.reload()
}
}
document.getElementById("submitnumber").onclick = checknumber
</script>
</body>
</html>
  • If you can confirm that input value will be number, then just check the length of the input value... Don't forget to use `.value` after element object. – vaku Aug 18 '20 at 16:22

2 Answers2

6

You're comparing an HTML element to a number. You want to compare a number to a number, by:

  1. Using the .value property on the element to get the string, and

  2. Parsing that string to a number (you have lots of different ways to do this depending on your use case; see this answer for a list of them)

For instance:

var tendigitnum = Number(document.getElementById("inputnumber").value);

Live Example:

function checknumber() {
  var tendigitnum = Number(document.getElementById("inputnumber").value)
  if (tendigitnum >= 1000000000 && tendigitnum <= 9999999999) {
    alert("You entered the number" + tendigitnum + ".")
  } else {
    alert("The page will refresh. Please enter a valid number.")
    location.reload()
  }
}
document.getElementById("submitnumber").onclick = checknumber
<p>Enter a 10 digit number between 1000000000 and 9999999999.</p>
<textarea id="inputnumber"></textarea>
<button type="button" id="submitnumber">Check</button>

On modern browsers you could use a number input:

<input type="number" id="inputnumber">

and use its valueAsNumber property instead of value, since valueAsNumber will already be a number. You can even add the range validation to the input. More on MDN.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You need to check the value in your element, in your code you are checking element

Biju Kalanjoor
  • 532
  • 1
  • 6
  • 12