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>
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>
You could also do this
function myFunction() {
const value = parseInt(document.getElementById("input").value);
if (!Number.isNaN(value)) {
HasNumber.innerText = "Has Numbers";
} else {
HasNumber.innerText = "No Numbers";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.