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>
CodePudding user response:
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>