While building complex form, you might want users to input only numbers into textbox. HTML5 already provides input type number textbox for numbers only input box. But still you may want to user input type text because:
Well you can still use input type text and use Javascript to prevent user input other than number characters.
In this article, we will show how to use text field to input only numbers. We will use keycodes value to validate whether user input number key or text key. Based on that, we can show error message. Below condition we will use to check and prevent to input the key.
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
Here is the full code with error message if user input other key instead of numeric key:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Only numbers input textbox</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="my-3">Only numbers input textbox</h1>
<div class="row">
<div class="col-12">
<div class="mb-3">
<label for="number" class="form-label">Number</label>
<input type="number" class="form-control w-50" id="number" placeholder="123456">
<div class="alert alert-danger d-none mt-3 w-50" id="number-message">Only numbers allowed.</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#number").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$('#number-message').addClass('d-block').removeClass('d-none');
return false;
} else {
$('#number-message').addClass('d-none').removeClass('d-block');
}
});
});
</script>
</body>
</html>
This will return below view with error message.
I hope you liked this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to increase and decrease image size using JavaScript
Use the JavaScript width and&n...Laravel 7 Highcharts Tutorial Example
In this tutorial, i am going to show you...Automatically Adjust iFrame Height According to its Contents Using JavaScript
Use the contentWindow Property...Form Validation in React16 with Example
This is a React form validation step by...Some errors have been detected on the server, please look at the bottom of this window.
You might have already worked in phpMyAd...