How can I limit the html input field so that it accepts only numeric input?

I have an html input field, but only numeric data is data. How can I provide this?

+4
source share
6 answers

You can use HTML5 to check input type without using JavaScript. However, this method is not yet supported by all browsers.

<input type="number" name="quantity" min="1" max="5"> 

Use the following attributes to indicate restrictions (as described here ):

  • max - indicates the maximum allowed value
  • min - indicates the minimum acceptable value
  • step - indicates the intervals of the legal number
  • value - sets the default value
+10
source

You will need events to check if the entered text is a number or not. See Code Example

Js

 function isValidChar(char){ var txt = char; var found = false; var validChars = "0123456789"; //List of valid characters for(j=0;j<txt.length;j++){ //Will look through the value of text var c = txt.charAt(j); found = false; for(x=0;x<validChars.length;x++){ if(c==validChars.charAt(x)){ found=true; break; } } if(!found){ //If invalid character is found remove it and return the valid character(s). document.getElementById('txtFld').value = char.substring(0, char.length -1); break; } } } 

HTML

 <input type="text" id="txtFld" onKeyup="isValidChar(this.value);" /> 

See the working code here jsfiddle

Although the code is a bit long, you can minimize it if you know how to use regex or jquery.

0
source
 <input name="txtnumbersOnly" type="text" onkeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;"> 
-1
source

Number () is the function you want "123a" returns NAN

parseInt () truncates the final letters "123a" returns 123

 <input type="text" id="txtFld" onblur="if(!Number(this.value)){alert('not a number');}" /> 
-1
source

Try this code. work even on ctrl + v (paste) ...

 <SCRIPT Language ="VBScript"> sub onlyNumber(idBox) Set objInl = CreateObject("VBScript.RegExp") objInl.Global = True objInl.Pattern = "[^0-9\-\.]" document.getElementById(idBox).value = objInl.Replace(document.getElementById(idBox).value, "") set objInl = nothing end sub </SCRIPT> 

  <input type="text" id="txtFld" onKeyup="onlyNumber(this.id);" /> 

-1
source

Use java script function as an authentication tool. Or you can get jquery functions.

-2
source

Source: https://habr.com/ru/post/1347675/


All Articles