AlanWakeSnake
AlanWakeSnake

Reputation: 19

How to check for a number in a textbox using javascript HTML?

I need to check if the value input in a HTML textbox contains a number, this is what I'm using so far, but it's not working, can anyone help? The text box would be a mix of letters and numbers, but I want to check if there are any numbers at all.

<input id="input" type="text">
<button onclick="myFunction()">Submit</button>
<p id="HasNumber"></p>

<script>
function myFunction() {
if (document.getElementById("input").value >= '0' && value <= '9' {
HasNumber.innerText = "Has Numbers" ; }
else {
HasNumber.innerText = "No Numbers" ; }
}
</script>

Upvotes: 0

Views: 65

Answers (1)

Abdul Basit
Abdul Basit

Reputation: 450

You can check if input contain number by using Regex like Below Example:

<input id="input" type="text">
<button onclick="myFunction()">Submit</button>
<p id="HasNumber"></p>

<script>
  function myFunction() {
    const inputVal = document.getElementById("input").value;

    let matchPattern = inputVal.match(/\d+/g);

    if (matchPattern != null) {
      HasNumber.innerText = "Has Numbers" ; 
    } else {
      HasNumber.innerText = "No Numbers" ; 
    }
  }
</script>

Upvotes: 3

Related Questions