html numeric keyboard plus comma sign [duplicate] - html

I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.
How can I do this using jQuery?

Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.
jQuery
Try it yourself on JSFiddle.
There is no native jQuery implementation for this, but you can filter the input values of a text <input> with the following inputFilter plugin (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and all browsers since IE 9):
// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
$.fn.inputFilter = function(callback, errMsg) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop focusout", function(e) {
if (callback(this.value)) {
// Accepted value
if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
$(this).removeClass("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
// Rejected value - restore the previous one
$(this).addClass("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
// Rejected value - nothing to restore
this.value = "";
}
});
};
}(jQuery));
You can now use the inputFilter plugin to install an input filter:
$(document).ready(function() {
$("#myTextBox").inputFilter(function(value) {
return /^\d*$/.test(value); // Allow digits only, using a RegExp
},"Only digits allowed");
});
Apply your preferred style to input-error class. Here's a suggestion:
.input-error{
outline: 1px solid red;
}
See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!
Pure JavaScript (without jQuery)
jQuery isn't actually needed for this, you can do the same thing with pure JavaScript as well. See this answer.
HTML 5
HTML 5 has a native solution with <input type="number"> (see the specification), but note that browser support varies:
Most browsers will only validate the input when submitting the form, and not when typing.
Most mobile browsers don't support the step, min and max attributes.
Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see this question.
Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.
Try it yourself on w3schools.com.

Here is the function I use:
// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
You can then attach it to your control by doing:
$("#yourTextBoxName").ForceNumericOnly();

Inline:
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
Unobtrusive style (with jQuery):
$('input[name="number"]').keyup(function(e)
{
if (/\D/g.test(this.value))
{
// Filter non-digits from input value.
this.value = this.value.replace(/\D/g, '');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number">

You could just use a simple JavaScript regular expression to test for purely numeric characters:
/^[0-9]+$/.test(input);
This returns true if the input is numeric or false if not.
or for event keycode, simple use below :
// Allow: backspace, delete, tab, escape, enter, ctrl+A and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
var charValue = String.fromCharCode(e.keyCode)
, valid = /^[0-9]+$/.test(charValue);
if (!valid) {
e.preventDefault();
}

You can use on input event like this:
$(document).on("input", ".numeric", function() {
this.value = this.value.replace(/\D/g,'');
});
But, what's this code privilege?
It works on mobile browsers(keydown and keyCode have problem).
It works on AJAX generated content too, because We're using "on".
Better performance than keydown, for example on paste event.

Short and sweet - even if this will never find much attention after 30+ answers ;)
$('#number_only').bind('keyup paste', function(){
this.value = this.value.replace(/[^0-9]/g, '');
});

Use JavaScript function isNaN,
if (isNaN($('#inputid').val()))
if (isNaN(document.getElementById('inputid').val()))
if (isNaN(document.getElementById('inputid').value))
Update:
And here a nice article talking about it but using jQuery: Restricting Input in HTML Textboxes to Numeric Values

$(document).ready(function() {
$("#txtboxToFilter").keydown(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 ) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});
});
Source: http://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values

I use this in our internal common js file. I just add the class to any input that needs this behavior.
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});

Simpler one for me is
jQuery('.plan_eff').keyup(function () {
this.value = this.value.replace(/[^1-9\.]/g,'');
});

Why so complicated? You don't even need jQuery because there is a HTML5 pattern attribute:
<input type="text" pattern="[0-9]*">
The cool thing is that it brings up a numeric keyboard on mobile devices, which is way better than using jQuery.

You can do the same by using this very simple solution
$("input.numbers").keypress(function(event) {
return /\d/.test(String.fromCharCode(event.keyCode));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="numbers" name="field_name" />
I referred to this link for the solution. It works perfectly!!!

You can try the HTML5 number input:
<input type="number" value="0" min="0">
For non-compliant browsers there are Modernizr and Webforms2 fallbacks.

The pattern attribute in HTML5 specifies a regular expression that the element's value is checked against.
<input type="text" pattern="[0-9]{1,3}" value="" />
Note: The pattern attribute works with the following input types: text, search, url, tel, email, and password.
[0-9] can be replaced with any regular expression condition.
{1,3} it represents minimum of 1 and maximum of 3 digit can be entered.

Something fairly simple using jQuery.validate
$(document).ready(function() {
$("#formID").validate({
rules: {
field_name: {
numericOnly:true
}
}
});
});
$.validator.addMethod('numericOnly', function (value) {
return /^[0-9]+$/.test(value);
}, 'Please only enter numeric values (0-9)');

Here is two different approaches:
Allow numeric values with decimal point
Allow numeric values without decimal point
APPROACH 1:
$("#approach1").on("keypress keyup blur",function (e) {
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Numeric with decimal point</h2><br/>
<span>Enter Amount</span>
<input type="text" name="amount" id="approach1">
APPROACH 2:
$("#approach2").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Numeric without decimal point</h2><br/>
<span>Enter Amount</span>
<input type="text" name="amount" id="approach2">

try it within html code it self like onkeypress and onpast
<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false">

If have a smooth OneLiner:
<input type="text" onkeypress="return /[0-9]/i.test(event.key)" >

function suppressNonNumericInput(event){
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
}

I came to a very good and simple solution that doesn't prevent the user from selecting text or copy pasting as other solutions do. jQuery style :)
$("input.inputPhone").keyup(function() {
var jThis=$(this);
var notNumber=new RegExp("[^0-9]","g");
var val=jThis.val();
//Math before replacing to prevent losing keyboard selection
if(val.match(notNumber))
{ jThis.val(val.replace(notNumber,"")); }
}).keyup(); //Trigger on page load to sanitize values set by server

You can use this JavaScript function:
function maskInput(e) {
//check if we have "e" or "window.event" and use them as "event"
//Firefox doesn't have window.event
var event = e || window.event
var key_code = event.keyCode;
var oElement = e ? e.target : window.event.srcElement;
if (!event.shiftKey && !event.ctrlKey && !event.altKey) {
if ((key_code > 47 && key_code < 58) ||
(key_code > 95 && key_code < 106)) {
if (key_code > 95)
key_code -= (95-47);
oElement.value = oElement.value;
} else if(key_code == 8) {
oElement.value = oElement.value;
} else if(key_code != 9) {
event.returnValue = false;
}
}
}
And you can bind it to your textbox like this:
$(document).ready(function() {
$('#myTextbox').keydown(maskInput);
});
I use the above in production, and it works perfectly, and it is cross-browser. Furthermore, it does not depend on jQuery, so you can bind it to your textbox with inline JavaScript:
<input type="text" name="aNumberField" onkeydown="javascript:maskInput()"/>

I think it will help everyone
$('input.valid-number').bind('keypress', function(e) {
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
})

Here is a quick solution I created some time ago. you can read more about it in my article:
http://ajax911.com/numbers-numeric-field-jquery/
$("#textfield").bind("keyup paste", function(){
setTimeout(jQuery.proxy(function() {
this.val(this.val().replace(/[^0-9]/g, ''));
}, $(this)), 0);
});

This is why I recently wrote to accomplish this. I know this has already been answered but I'm leaving this for later uses.
This method only allows 0-9 both keyboard and numpad, backspaces, tab, left and right arrows (normal form operations)
$(".numbersonly-format").keydown(function (event) {
// Prevent shift key since its not needed
if (event.shiftKey == true) {
event.preventDefault();
}
// Allow Only: keyboard 0-9, numpad 0-9, backspace, tab, left arrow, right arrow, delete
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) {
// Allow normal operation
} else {
// Prevent the rest
event.preventDefault();
}
});

I wrote mine based off of #user261922's post above, slightly modified so you can select all, tab and can handle multiple "number only" fields on the same page.
var prevKey = -1, prevControl = '';
$(document).ready(function () {
$(".OnlyNumbers").keydown(function (event) {
if (!(event.keyCode == 8 // backspace
|| event.keyCode == 9 // tab
|| event.keyCode == 17 // ctrl
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105) // number on keypad
|| (event.keyCode == 65 && prevKey == 17 && prevControl == event.currentTarget.id)) // ctrl + a, on same control
) {
event.preventDefault(); // Prevent character input
}
else {
prevKey = event.keyCode;
prevControl = event.currentTarget.id;
}
});
});

You would want to allow tab:
$("#txtboxToFilter").keydown(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});

Here is an answer that uses jQuery UI Widget factory. You can customize what characters are allowed easily.
$('input').numberOnly({
valid: "0123456789+-.$,"
});
That would allow numbers, number signs and dollar amounts.
$.widget('themex.numberOnly', {
options: {
valid : "0123456789",
allow : [46,8,9,27,13,35,39],
ctrl : [65],
alt : [],
extra : []
},
_create: function() {
var self = this;
self.element.keypress(function(event){
if(self._codeInArray(event,self.options.allow) || self._codeInArray(event,self.options.extra))
{
return;
}
if(event.ctrlKey && self._codeInArray(event,self.options.ctrl))
{
return;
}
if(event.altKey && self._codeInArray(event,self.options.alt))
{
return;
}
if(!event.shiftKey && !event.altKey && !event.ctrlKey)
{
if(self.options.valid.indexOf(String.fromCharCode(event.keyCode)) != -1)
{
return;
}
}
event.preventDefault();
});
},
_codeInArray : function(event,codes) {
for(code in codes)
{
if(event.keyCode == codes[code])
{
return true;
}
}
return false;
}
});

This seems unbreakable.
// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
this.value = this.value.replace(/[^0-9\.]+/g, '');
if (this.value < 1) this.value = 0;
});
// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});

Need to make sure you have the numeric keypad and the tab key working too
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {
}
else {
event.preventDefault();
}
}

I wanted to help a little, and I made my version, the onlyNumbers function...
function onlyNumbers(e){
var keynum;
var keychar;
if(window.event){ //IE
keynum = e.keyCode;
}
if(e.which){ //Netscape/Firefox/Opera
keynum = e.which;
}
if((keynum == 8 || keynum == 9 || keynum == 46 || (keynum >= 35 && keynum <= 40) ||
(event.keyCode >= 96 && event.keyCode <= 105)))return true;
if(keynum == 110 || keynum == 190){
var checkdot=document.getElementById('price').value;
var i=0;
for(i=0;i<checkdot.length;i++){
if(checkdot[i]=='.')return false;
}
if(checkdot.length==0)document.getElementById('price').value='0';
return true;
}
keychar = String.fromCharCode(keynum);
return !isNaN(keychar);
}
Just add in input tag "...input ... id="price" onkeydown="return onlyNumbers(event)"..." and you are done ;)

Related

Restrict an HTML input to digits only, with maxlength 5 (ignore other characters)

I have read many similar questions, but could not find one that works for these 2 conditions (only digits input with maximum length of 5). I have tried different variations, one of them is:
<div class="input text">
<input id="zip" name="zip" type="number" min="0" max="99999" ng-model="formData.zip" placeholder="Type here..." class="input-medium" ng-init="0">
For this one I am still able to type in as many digits as I want, so the min max attributes do not really do anything.
A more aggressive approach that uses the keydown event and blocks all unwanted input via preventDefault:
Edit:
I've also included a version that allows for copy/pasting for comparison, but in this case you need to use keyup to allow the paste to occur before fixing the pasted content.
For any other key or key combination that you want to allow you can simply add them to the first if statement as allowed input.
/////////////////////////////////////////////////////
// Super strict version only allows numbers as input
/////////////////////////////////////////////////////
var input = document.getElementById('num');
input.addEventListener('keydown', function(event) {
// always allow backspace, delete, left/right arrow keys
if (event.which == 8 || event.which == 46 || event.which == 37 || event.which == 39) {
return;
}
// prevent all other input if already at 5 chars or not a number
else if (input.value.length >= 5 || event.which < 48 || event.which > 57) {
event.preventDefault();
return;
}
});
/////////////////////////////////////////////////////
// Version that allows for copy/pasting
/////////////////////////////////////////////////////
var inputPaste = document.getElementById('paste-num');
inputPaste.addEventListener('keydown', function(event) {
// always allow backspace, delete, left/right arrow, copy, paste, select all
if (event.which == 8 || event.which == 46 || event.which == 37 || event.which == 39 || (event.ctrlKey && event.which == 67) || (event.ctrlKey && event.which == 86) || (event.ctrlKey && event.which == 65)) {
return;
}
// prevent all other input if already at 5 chars or not a number
else if (inputPaste.value.length >= 5 || event.which < 48 || event.which > 57) {
event.preventDefault();
return;
}
});
// clean anything that gets pasted in
inputPaste.addEventListener('keyup', function(event) {
if (event.ctrlKey && event.which == 86) {
// remove non numbers
inputPaste.value = inputPaste.value.replace(/[^0-9]/g, "");
// trim to first 5 digits
inputPaste.value = inputPaste.value.substr(0, 5);
}
});
Numbers Only: <input id="num" name="num" placeholder="#####"> <br>
Numbers Only(can copy/paste):<input id="paste-num" name="paste-num" placeholder="#####">
Here's a way to do it. On keyup the handler checks the input value; if there are more than five characters, it doesn't let the user add any more. If a non-numeric character is entered, the function removes it.
UPDATE: This code can now handle inserting numbers in the beginning or middle of the pack as well when five characters are already present.
var inputEl = document.getElementById('zip');
var prev = "";
inputEl.addEventListener('keyup', function(e) {
if (e.which == 8) { // if backspace
prev = inputEl.value;
return;
}
// check for >5 characters
if (inputEl.value.length > 5) {
if (e.which < 48 || e.which > 57) { // if new char is a number
inputEl.value = prev;
} else {
inputEl.value = inputEl.value.slice(0, inputEl.value.length - 1);
}
if (inputEl.value.length > 5) { // if still >5 after parsing
inputEl.value = inputEl.value.slice(0, 5);
}
}
// check for a digit (code 48 to 57)
else if (e.which < 48 || e.which > 57) {
(inputEl.value.length > 1) ? inputEl.value = prev: inputEl.value = "";
}
prev = inputEl.value;
});
inputEl.focus();
<div class="input text">
<input id="zip" name="zip" placeholder="Type here...">
</div>
(Focus was added to the input box for ease of testing.)

Input type number is not working in firefox

I have an issue.I have an input field which type is number but its taking any alphabet in mozila firefox browser.Its working great in chrome but not working in firefox.I need it should work as chrome and not take any alphabet.I am using Mozila firefox version 48.0.I am explaining my code below.
<input type="number" class="form-control oditek-form" ng-model="type" name="type" step="1" min="0" placeholder="Add Type">
Please help me.
i am using firefox too, i had the same issue developing my input type number typing caracters and spaces etc...
i have found the solution of the tag pattern="[1-9]", but unfortunately it didn't work for me. After a wile of searching without any result, i decided to develop my own function.
anyway i m using angular 2 in this examples, its almost similar to javascript, so you can use this code in every case :
here is the html :
<input class="form-control form-control-sm" id="qte" type="number" min="1" max="30" step="1" [(ngModel)]="numberVoucher"
(keypress)="FilterInput($event)" />
here is the function FilterInput :
FilterInput(event: any) {
let numberEntered = false;
if ((event.which >= 48 && event.which <= 57) || (event.which >= 37 && event.which <= 40)) { //input number entered or one of the 4 directtion up, down, left and right
//console.log('input number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
numberEntered = true;
}
else {
//input command entered of delete, backspace or one of the 4 directtion up, down, left and right
if ((event.keyCode >= 37 && event.keyCode <= 40) || event.keyCode == 46 || event.which == 8) {
//console.log('input command entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
}
else {
//console.log('input not number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
event.preventDefault();
}
}
// input is not impty
if (this.validForm) {
// a number was typed
if (numberEntered) {
let newNumber = parseInt(this.numberVoucher + '' + String.fromCharCode(event.which));
console.log('new number : ' + newNumber);
// checking the condition of max value
if ((newNumber <= 30 && newNumber >= 1) || Number.isNaN(newNumber)) {
console.log('valid number : ' + newNumber);
}
else {
console.log('max value will not be valid');
event.preventDefault();
}
}
// command of delete or backspace was types
if (event.keyCode == 46 || event.which == 8) {
if (this.numberVoucher >= 1 && this.numberVoucher <= 9) {
console.log('min value will not be valid');
this.numberVoucher = 1;
//event.preventDefault();
this.validForm = true;
}
}
}
// input is empty
else {
console.log('this.validForm = true');
this.validForm = false;
}
};
in this function i had to just let the keypress of numbers, direction, deletes enter.
Note: The min attribute of the tag is not supported in Internet Explorer 9 and earlier versions, or in Firefox.
Source: http://www.w3schools.com/tags/att_input_min.asp

How to make HTML input tag only accept numbers?

How to make HTML input tag only accept numbers?
I need to make sure that input field only takes numbers as input
value.
I want the user to be unable to type in any other characters other
than numbers.
User manually enters the number not a number scroll bar.
I am using the Meteor Js.And the code as shown below.
App.html
<head>
<title App</title>
</head>
<body>
{{> main}}
</body>
<template name="main">
<h1>Welcome to TICTACTOE App</h1>
<p><b>Layout Number :</b> <input type="text" id="no"></p>
</template>
App.js
if (Meteor.isClient)
{
Template.main.events
({
'keydown input#no' : function ()
{
// template data, if any, is available in 'this'
if (event.which == 13)
{ // 13 is the enter key event
console.log("You pressed enter key");
}
}
});
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
});
}
This should help you.
<input type="number" />
:)
Or Best way to use jQuery with keycodes:
jQuery("#yourInputId").keydown(function(event) {
// Allow: backspace, delete, tab, escape, enter and .
if ( jQuery.inArray(event.keyCode,[46,8,9,27,13,190]) !== -1 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
See DEMO.
if you use HTML5 then
<input type="number" />
else
<script>
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
</script>
<input type="text" onkeypress="return isNumberKey(event);">
With HTML5 it's easy:
<input type="number" />
If HTML5 is not supported use jQuery events: Live Demo
<label for="number">Number: </label>
<input type="text" name="number" id="number" />
<script>
$('#number').keydown(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
$(this).keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
});
</script>
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="someid" name="number" onkeypress="return isNumberKey(event)"/>
will work only with HTML 5.
If you want it to work for older browser as well you have to take help of javascript.
Try this
<input name="amount" type="text" value="Only number in here"/>
<script>
$('input[name=amount]').keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
</script>
You can also use the pattern attribute in html5:
<input type="text" name="name" pattern="[0-9]" title="Title" />
On any input you need filter, you only need put the onkeydown="return onlynumbers(event);"
code.
This is a generic code that will work on old HTML and does not need jQuery. :)
<script type="text/javascript">
function onlynumbers(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
</script>
<input type="text" onkeydown="return onlynumbers(event);">

Texbox restrict characters and symbols and only allow numeric values with only one decimal point

Texbox restrict entering characters and symbols and only allow numeric values with only one decimal point.maximum length 4 and one value after decimal point.For eg: .2,12.3,1444
Here is the code in html to allow only one decimal point in a textbox:
<script type="text/javascript" language="javascript">
function isNumberKey(evt) {
var charCode = (evt.charCode) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
var input = document.getElementById("txtChar").value;
var len = document.getElementById("txtChar").value.length;
var index = document.getElementById("txtChar").value.indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index >0 || index==0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 2) {
return false;
}
}
if (charCode == 46 && input.split('.').length >1) {
return false;
}
I want to done this in asp.net using c#.This code is not properly working in asp.net.
Please Check this Link - Validate Input Field which will allows Only Float...
$(function(){
$('.float-input').keyup(function(e){
var entered_value = $(this).val();
var regexPattern = /^\d{0,8}(\.\d{1,2})?$/;
//Allow only Number as well 0nly 2 digit after dot(.)
if(regexPattern.test(entered_value)) {
$(this).css('background-color', 'white');
$('.err-msg').html('');
} else {
$(this).css('background-color', 'red');
$('.err-msg').html('Enter a valid Decimal Number');
}
});
});

Is there any way to prevent input type="number" getting negative values?

I want to get only positive values, is there any way to prevent it using only html
Please don't suggest validation method
Use the min attribute like this:
<input type="number" min="0">
For me the solution was:
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
Edit
As suggested on the comments with a minor change to work if 0 is the min value.
<input type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
I was not satisfied with #Abhrabm answer because:
It was only preventing negative numbers from being entered from
up/down arrows, whereas user can type negative number from keyboard.
Solution is to prevent with key code:
// Select your input element.
var number = document.getElementById('number');
// Listen for input event on numInput.
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
<form action="" method="post">
<input type="number" id="number" min="0" />
<input type="submit" value="Click me!"/>
</form>
Clarification provided by #Hugh Guiney:
What key codes are being checked:
95, < 106 corresponds to Numpad 0 through 9;
47, < 58 corresponds to 0 through 9 on the Number Row; and 8 is
Backspace.
So this script is preventing invalid key from being entered in input.
This code is working fine for me. Can you please check:
<input type="number" name="test" min="0" oninput="validity.valid||(value='');">
Easy method:
<input min='0' type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
I wanted to allow decimal numbers and not clear the entire input if a negative was inputted. This works well in chrome at least:
<input type="number" min="0" onkeypress="return event.charCode != 45">
The #Manwal answer is good, but i like code with less lines of code for better readability. Also i like to use onclick/onkeypress usage in html instead.
My suggested solution does the same:
Add
min="0" onkeypress="return isNumberKey(event)"
to the html input and
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode;
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
as a javascript function.
As said, it does the same. It's just personal preference on how to solve the problem.
Here's an angular 2 solution:
create a class OnlyNumber
import {Directive, ElementRef, HostListener} from '#angular/core';
#Directive({
selector: '[OnlyNumber]'
})
export class OnlyNumber {
// Allow decimal numbers. The \. is only allowed once to occur
private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) {
}
#HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
let current: string = this.el.nativeElement.value;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
add OnlyNumber to declarations in app.module.ts and use like it like this anywhere in your app
<input OnlyNumber="true">
Just for reference: with jQuery you can overwrite negative values on focusout with the following code:
$(document).ready(function(){
$("body").delegate('#myInputNumber', 'focusout', function(){
if($(this).val() < 0){
$(this).val('0');
}
});
});
This does not replace server side validation!
Restrict the charcter (-) & (e) in type Number
<input type="number" onkeydown="return event.keyCode !== 69 && event.keyCode !== 189" />
Demo: https://stackblitz.com/edit/typescript-cwc9ge?file=index.ts
oninput="this.value=(this.value < Number(this.min) || this.value > Number(this.max)) ? '' : this.value;"
simply use min="0"
<v-text-field
v-model="abc"
class="ml-1 rounded-0"
outlined
dense
label="Number"
type="number"
min="0">
</v-text-field>
Just adding another way of doing this (using Angular) if you don't wanna dirt the HTML with even more code:
You only have to subscribe to the field valueChanges and set the Value as an absolute value (taking care of not emitting a new event because that will cause another valueChange hence a recursive call and trigger a Maximum call size exceeded error)
HTML CODE
<form [formGroup]="myForm">
<input type="number" formControlName="myInput"/>
</form>
TypeScript CODE (Inside your Component)
formGroup: FormGroup;
ngOnInit() {
this.myInput.valueChanges
.subscribe(() => {
this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
});
}
get myInput(): AbstractControl {
return this.myForm.controls['myInput'];
}
<input type="number" name="credit_days" pattern="[^\-]+"
#credit_days="ngModel" class="form-control"
placeholder="{{ 'Enter credit days' | translate }}" min="0"
[(ngModel)]="provider.credit_days"
onkeypress="return (event.charCode == 8 || event.charCode == 0 ||
event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <=
57" onpaste="return false">
The answer to this is not helpful. as its only works when you use up/down keys, but if you type -11 it will not work. So here is a small fix that I use
this one for integers
$(".integer").live("keypress keyup", function (event) {
// console.log('int = '+$(this).val());
$(this).val($(this).val().replace(/[^\d].+/, ""));
if (event.which != 8 && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
});
this one when you have numbers of price
$(".numeric, .price").live("keypress keyup", function (event) {
// console.log('numeric = '+$(this).val());
$(this).val($(this).val().replace(/[^0-9\,\.]/g, ''));
if (event.which != 8 && (event.which != 44 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
This solution allows all keyboard functionality including copy paste with keyboard. It prevents pasting of negative numbers with the mouse. It works with all browsers and the demo on codepen uses bootstrap and jQuery. This should work with non english language settings and keyboards. If the browser doesn't support the paste event capture (IE), it will remove the negative sign after focus out. This solution behaves as the native browser should with min=0 type=number.
Markup:
<form>
<input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
<input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>
Javascript
$(document).ready(function() {
$("input.positive-numeric-only").on("keydown", function(e) {
var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
e.preventDefault();
}
});
$("input.positive-numeric-only").bind("paste", function(e) {
var numbers = e.originalEvent.clipboardData
.getData("text")
.replace(/[^0-9^.^,]/g, "");
e.preventDefault();
var the_val = parseFloat(numbers);
if (the_val > 0) {
$(this).val(the_val.toFixed(2));
}
});
$("input.positive-numeric-only").focusout(function(e) {
if (!isNaN(this.value) && this.value.length != 0) {
this.value = Math.abs(parseFloat(this.value)).toFixed(2);
} else {
this.value = 0;
}
});
});
Here is a solution that worked best of me for a QTY field that only allows numbers.
// Only allow numbers, backspace and left/right direction on QTY input
if(!((e.keyCode > 95 && e.keyCode < 106) // numpad numbers
|| (e.keyCode > 47 && e.keyCode < 58) // numbers
|| [8, 9, 35, 36, 37, 39].indexOf(e.keyCode) >= 0 // backspace, tab, home, end, left arrow, right arrow
|| (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + A
|| (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + C
|| (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + X
|| (e.keyCode == 86 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + V
)) {
return false;
}
If Number is Negative or Positive Using ES6’s Math.Sign
const num = -8;
// Old Way
num === 0 ? num : (num > 0 ? 1 : -1); // -1
// ES6 Way
Math.sign(num); // -1