To restrict input to allow only numbers and decimal point in a textbox with JavaScript, we can call the string match method to validate the input value. form. onsubmit = () => { return textarea. value.
To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places.
We will use %. 2f to limit a given floating-point number to two decimal places.
The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.
If you want to restrict input (as opposed to validation), you could work with the key events. something like this:
<input type="text" class="numbersOnly" value="" />
And:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
This immediately lets the user know that they can't enter alpha characters, etc. rather than later during the validation phase.
You'll still want to validate because the input might be filled in by cutting and pasting with the mouse or possibly by a form autocompleter that may not trigger the key events.
There is a new and very simple solution for this:
It allows you to use any kind of input filter on a text
<input>
, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.
See this answer or try it yourself on JSFiddle.
I've successfully implemented many forms with the jquery.numeric plugin.
$(document).ready(function(){
$(".numeric").numeric();
});
Moreover this works with textareas also!
However, note that Ctrl+A, Copy+Paste (via context menu) and Drag+Drop will not work as expected.
With wider support for the HTML 5 standard, we can use pattern
attribute and number
type for input
elements to restrict number only input. In some browsers (notably Google Chrome), it works to restrict pasting non-numeric content as well. More information about number
and other newer input types is available here.
I thought that the best answer was the one above to just do this.
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
but I agree that it is a bit of a pain that the arrow keys and delete button snap cursor to the end of the string ( and because of that it was kicked back to me in testing)
I added in a simple change
$('.numbersOnly').keyup(function () {
if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
this.value = this.value.replace(/[^0-9\.]/g, '');
}
});
this way if there is any button hit that is not going to cause the text to be changed just ignore it. With this you can hit arrows and delete without jumping to the end but it clears out any non numeric text.
The jquery.numeric plugin has some bugs that I notified the author of. It allows multiple decimal points in Safari and Opera, and you can't type backspace, arrow keys, or several other control characters in Opera. I needed positive integer input so I ended up just writing my own in the end.
$(".numeric").keypress(function(event) {
// Backspace, tab, enter, end, home, left, right
// We don't support the del key in Opera because del == . == 46.
var controlKeys = [8, 9, 13, 35, 36, 37, 39];
// IE doesn't support indexOf
var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
// Some browsers just don't raise events for control keys. Easy.
// e.g. Safari backspace.
if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
(49 <= event.which && event.which <= 57) || // Always 1 through 9
(48 == event.which && $(this).attr("value")) || // No 0 first digit
isControlKey) { // Opera assigns values for control keys.
return;
} else {
event.preventDefault();
}
});
No more plugins, jQuery has implemented its own jQuery.isNumeric() added in v1.7.
jQuery.isNumeric( value )
Determines whether its argument is anumber.
$.isNumeric( "-10" ); // true
$.isNumeric( 16 ); // true
$.isNumeric( 0xFF ); // true
$.isNumeric( "0xFF" ); // true
$.isNumeric( "8e5" ); // true (exponential notation string)
$.isNumeric( 3.1415 ); // true
$.isNumeric( +10 ); // true
$.isNumeric( 0144 ); // true (octal integer literal)
$.isNumeric( "" ); // false
$.isNumeric({}); // false (empty object)
$.isNumeric( NaN ); // false
$.isNumeric( null ); // false
$.isNumeric( true ); // false
$.isNumeric( Infinity ); // false
$.isNumeric( undefined ); // false
Here is an example of how to tie the isNumeric() in with the event listener
$(document).on('keyup', '.numeric-only', function(event) {
var v = this.value;
if($.isNumeric(v) === false) {
//chop off the last char entered
this.value = this.value.slice(0,-1);
}
});
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