Trying to limit the user to only enter numbers in a text field.
Asked
Active
Viewed 266 times
0
-
2You need to use ```number``` input. – Alexander Popov Mar 20 '16 at 07:25
-
Refer to the answers at http://stackoverflow.com/questions/13952686/how-to-make-html-input-tag-only-accept-numerical-values – Haneez Mar 20 '16 at 07:31
-
Please use the search before you ask a new question. – Felix Kling Mar 20 '16 at 08:03
1 Answers
0
I am assuming you're talking about FORM in HTML. There are several ways to do that:
Input type
As Alexander proposed, you can set the input
type to number
.
For example, in this form the user is required to provide his/her ID number before submitting. Please note that, the type
is set to number
.
<!DOCTYPE html>
<html>
<body>
<form action="action_page.php">
ID Number:<br>
<input type="number" name="id" value="0">
<br><br>
<input type="submit">
</form>
</body>
</html>
Javascript
you can set a javascript function that validates the input on-submit.
<script>
function validateForm() {
var x = document.forms["myForm"]["id"].value;
if (x == null || x.search(/^\d+$/i) < 0) {
alert("ID must be a number");
return false;
}
}
</script>
<form name="myForm" action="demo_form.php"
onsubmit="return validateForm()" method="post">
ID: <input type="text" name="id">
<input type="submit" value="Submit">
</form>
Here is another example on W3Schools
AngularJS
There is a lot of buzz around AngularJS and I assume you may want to go there in some point. Fortunately, the AngularJS documents regard that subject are pretty understandable and straightforward or at least to me.
Here are some examples:

Community
- 1
- 1

boaz_shuster
- 2,825
- 20
- 26