Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't allow typing alphabetic characters in a <input type=number />

Tags:

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.

like image 215
user79307 Avatar asked Aug 14 '13 05:08

user79307


People also ask

How do you restrict the input field alphabets?

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.

How do you stop typing in input type number?

$("[type='number']"). keypress(function (evt) { evt. preventDefault(); });

How do I restrict alphabets in a text box?

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.


2 Answers

You can use jquery.numeric plugin.

See here similar question.

$(document).ready(function(){    $(".numeric").numeric(); }); 
like image 192
mihai.ciorobea Avatar answered Oct 21 '22 06:10

mihai.ciorobea


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)"> 
like image 21
Sandip Avatar answered Oct 21 '22 04:10

Sandip