How do I restrict "+ - e , ." from HTML number input? - html

I've got a HTML number input element: <input type="number">.
Problem is that I can also input following characters: + - e E , . which I don't want the user to be able to write.
How do I restrict these?

Edit: Boris K has got an even better answer.
Original answer:
This would be a way to accomplish that:
var ageInput = document.getElementById("age")
ageInput.addEventListener("keydown", function(e) {
// prevent: "e", "=", ",", "-", "."
if ([69, 187, 188, 189, 190].includes(e.keyCode)) {
e.preventDefault();
}
})
<input type="number" id="age">

You shouldn't rely only on <input type="number">, because that would work only in moderns browsers with different behaviours depending on the browser.
Use jQuery to perform additional checks (with a regexp):
$('#my-input').keypress(function() {
var inputValue = $(this).val();
var reg = /^\d+$/;
if (reg.test(inputValue)){
alert("input value is integer");
} else {
alert("input value is not an integer");
}
});

To restrict those values, catch the keypress event with javascript, and prevent those characters from being entered.
We capture the keyCode from the event, and restrict the input to not allow those characters by their ASCII codes.
document.getElementById('my-number-input').onkeypress = function(e) {
if(!e) e = window.event;
var keyCode = e.keyCode || e.which;
if(!((keyCode >= 48 && keyCode <= 57) ||
(keyCode >=96 && keyCode <= 105))) {
e.preventDefault(); //This stops the character being entered.
}
}
The IF statement above states that if the keycode is not in the range of 0-9 on the keyboard (including the number pad), then do not add the character to the input.

Related

Automatically add comma for monetary values in a form?

Not sure if I described my question well, but basically here's what I've got right now:
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
Right now if you enter 1000 it will add comma like this: 1,000
What I want is the number to act as a cent.
So if I write 100 it will add a dot here: 1.00
If 1000, then 10.00
If 10000 then 100.00
If 100000 then 1,000.00
and so on.
basically I want the number to be a cent and add commas and dots with a jQuery accordingly.
But I don't want them to be submitted.
I have seen this being done in ad networks, kubikads for example.
The numbers should be submitted without commas and dots.
The jQuery code in the above code seems very confusing to me .
If anyone have a ready made script or know what to modify in the script to achieve this, I would greatly appreciate
A little dirty... but it works! You can just pop off the decimal and store it while you add the commas.
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/^0+/,"")
.split(/(\d{0,2})$/)
.join(".")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
.replace(/.$/,"")
});
});
$('#myform').submit(function(e) {
e.currentTarget[0].value = e.currentTarget[0].value
.replace(/\D/g, "")
console.log(e.currentTarget[0].value)
return false; // return false to cancel form action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form id="myform">
<input class="number">
</form>
This should do it...
var num = '132406'; /Your original unformatted number
var ret = '';
var p = 0;
for (let i = num.length; i > 0; i--) {
p = p + 1;
if (p == 3 && ret.includes('.') == false) {
ret = '.' + ret;
p = 0;
} else if (p % 3 == 0 ) {
ret = ',' + ret;
}
ret = num.substring(i - 1, i) + ret;
}
console.log(ret);

How to prevent the use of some characters in an input field

In a form I use an input field to rename a filename. How can I prevent the use of / and . ??
All letters and numbers are ok.
I tried with pattern="" but don't know what to put there...
If using jquery, then below code will allow only alphanumeric values
$('#yourInputTag').bind('keyup', function(e) {
$(this).val($(this).val().replace(/[^0-9a-zA-Z]/g, ''));
if (e.which >= 97 && e.which <= 122) {
var newKey = e.which - 32;
e.keyCode = newKey;
e.charCode = newKey;
}
$(this).val(($(this).val()));
});
You can bind a onkeyup function with your input which will fire everytime a key is pressed and replace your input value there.
<html>
<input type="text" placeholder="enter value" onkeyup="checkValueWithRegex()" id="myInput">
<script>
function checkValueWithRegex() {
var value = document.getElementById("myInput").value;
value = value.replace(/[^a-zA-Z0-9]/g, '');
document.getElementById("myInput").value = value;
}
</script>
</html>

html type="number" : Show always 2 digits after dot?

in a type="number" input, i would like to show 2 digits after dot like "2.50"
if a try
<input name="price" type="number" step="0.01" value="2.5">
this show me "2.5" and not "2.50"
Have you a method to do this ? HTML5 pure or with javascript ?
you need to use Jquery or JavaScript for that what ever you want but this solution in Jquery
You Can't go for more than 2 number
//Use keyup to capture user input & mouse up to catch when user is changing the value with the arrows
$('.trailing-decimal-input').on('keyup mouseup', function (e) {
// on keyup check for backspace & delete, to allow user to clear the input as required
var key = e.keyCode || e.charCode;
if (key == 8 || key == 46) {
return false;
};
// get the current input value
let correctValue = $(this).val().toString();
//if there is no decimal places add trailing zeros
if (correctValue.indexOf('.') === -1) {
correctValue += '.00';
}
else {
//if there is only one number after the decimal add a trailing zero
if (correctValue.toString().split(".")[1].length === 1) {
correctValue += '0'
}
//if there is more than 2 decimal places round backdown to 2
if (correctValue.toString().split(".")[1].length > 2) {
correctValue = parseFloat($(this).val()).toFixed(2).toString();
}
}
//update the value of the input with our conditions
$(this).val(correctValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="my-number-input" class="form-control trailing-decimal-input" type="number" min="0.01" step="0.01" value="2.50" />
you can preview or edit code Here on JSFiddle
You can solve by script Like :
<script type="text/javascript">
$(document).ready(function() {
var num = 2.5;
var n = num.toFixed(2);
alert(n);
});
</script>
<script type="text/javascript">
$(document).ready(function() {
var num = 2.500;
var n = num.toFixed(1);
alert(n);
});
</script>

input number accepts trailing dashes

How can I block input number of accepting trailing dashes (values like "10-" or "10-7")? If you enter wrong format Input doesn't give you any value.
<input name="Number" type="number">
You can use the pattern attribute:
<input name="Number" type="number" pattern="[0-9]*">
This is not possible without validating the value of the input.
Since it is a string representing the number there is no way to be sure that string may be representing numeric values or not.
The Permitted attributes will not give you the ability to validate the value of the number input control.
One way to do this with the help of JavaScript could look like this.
var numInput = document.querySelector('input');
// Listen for input event on numInput.
numInput.addEventListener('input', function(){
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
}, false)
<input name="Number" type="number" min="0" >
function validate(evt) {
l = document.getElementsByTagName('input')[0].value.length;
if(l === 0 && String.fromCharCode(evt.keyCode) === '-') return
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
<input type='text' onkeypress='validate(event)' />
bind keydown event to the input, if keyCode == 189 or keyCode == 69, preventDefault()

html numeric keyboard plus comma sign [duplicate]

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 ;)