I need to have a textbox, where, whenever typed inside should ONLY allow numbers [0-9]. I've used type="number"
which definitely holds the client side validation but also allows to type other alphabets. I can do it by tracking each keydown and matching with regex but I was wondering if there is any way I can restrict to type using only html tags and NOT defining any functions in JavaScript to compare in each keydown?
Code not sufficient to do so is:
<input type="number" id="txt_number" maxlength="70" name="txt_name" placeholder="Number">
Any help is appreciated.
The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.
$("[type='number']"). keypress(function (evt) { evt. preventDefault(); });
JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters) This JavaScript function will be used to restrict alphabets and special characters in Textbox , only numbers, delete, arrow keys and backspace will be allowed.
You can use jquery.numeric plugin.
See here similar question.
$(document).ready(function(){ $(".numeric").numeric(); });
Try this
define javascript function
function for allowed number with decimal as below
function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; }
function for allowed only number not decimal is as below
function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if ((charCode < 48 || charCode > 57)) return false; return true; }
Html
<input type="number" id="txt_number" maxlength="70" name="txt_name" placeholder="Number" onkeypress="return isNumberKey(event)">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With