Allow only numbers into a input text box - html

I have a number input text box and I want to allow the user to edit but do not want to allow the user to enter any other text except numbers. I want them only to be able to use the arrows on the number input box.
<input type = "number" min="0" max="10" step="0.5" input id="rating" name = "rating" class = "login-input" placeholder = "Rating 1-5:" value="0">

You can achieve this by pure JavaScript. Create this function that you can reuse in your script.
function allowNumbersOnly(e) {
var code = (e.which) ? e.which : e.keyCode;
if (code > 31 && (code < 48 || code > 57)) {
e.preventDefault();
}
}
You may preferably call this onkeypress event handler.
<input type="text" id="onlyNumbers" onkeypress="allowNumbersOnly(event)" />
function allowNumbersOnly(e) {
var code = (e.which) ? e.which : e.keyCode;
if (code > 31 && (code < 48 || code > 57)) {
e.preventDefault();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
Try editing in me:
<input type="text" id="onlyNumbers" onkeypress="allowNumbersOnly(event)" />
</body>
</html>
However, I would recommend the unobtrusive style of writing JS using because it is good to keep the HTML semantic and away from pollution. You can execute the function on event handler that we would attach to this text box using vanilla JavaScript or jQuery.
function allowNumbersOnly(e) {
var code = (e.which) ? e.which : e.keyCode;
if (code > 31 && (code < 48 || code > 57)) {
e.preventDefault();
}
}
// using classic addEventListener method:
document.getElementById('onlyNumbers').addEventListener('keypress', function(e){ allowNumbersOnly(e);
}, false);
//using jQuery
$(function(){
$('#onlyNumbers2').keypress(function(e) {
allowNumbersOnly(e);
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div>
Using addEventListener: <input type="text" id="onlyNumbers" />
</div>
<div>
Using jQuery: <input type="text" id="onlyNumbers2" />
</div>
</body>
</html>
To restrict every character you can just simply use e.preventDefault().
Besides, you can also use return false instead but preventDefault() is better in this case and return false should be chosen wisely. It is good to know the difference between both of them.

document.getElementById('rating').onkeypress = function() { return false; }
This will prevent the default behavior of keypresses on that element i.e. text showing up.

HTML
<input type="text" class="IntOnly">
Javascript
let ele = document.getElementsByClassName('IntOnly');
for (const e of ele) {
//e.addEventListener('change', filterNonIntOut.bind(null, e));
//e.addEventListener('paste', filterNonIntOut.bind(null, e));
e.addEventListener('input', filterNonIntOut.bind(null, e));
}
function filterNonIntOut(theTextbox) {
//console.log(ele);
let startPos = theTextbox.selectionStart;
let endPos = theTextbox.selectionEnd;
let str = theTextbox.value;
str = str.trim();
if (str == '') {
theTextbox.value = '';
return;
}
let result = "";
for (var i = 0; i < str.length; i++) {
let ch = str.charAt(i);
//console.log(ch);
if (ch === '1'
|| ch === '2'
|| ch === '3'
|| ch === '4'
|| ch === '5'
|| ch === '6'
|| ch === '7'
|| ch === '8'
|| ch === '9'
|| ch === '0'
) {
result += ch;
}
else {
startPos -= 1;
endPos -= 1;
}
}
theTextbox.value = result;
theTextbox.focus();
theTextbox.setSelectionRange(startPos, endPos);
}

Related

How to create Custom Textarea using html and jquery

$(document).ready(function() {
$("textarea").on('keydown keypress keyup', function(e) {
if (e.keyCode == 8 || e.keyCode == 46) {
return true;
}
var maxRowCount = $(this).attr("rows") || 4;
var lineCount = $(this).val().split('\n').length;
if (e.keyCode == 13) {
if (lineCount == maxRowCount) {
return false;
}
}
var jsElement = $(this)[0];
if (jsElement.clientHeight < jsElement.scrollHeight) {
var text = $(this).val();
text = text.slice(0, -1);
$(this).val(text);
return false;
}
});
});
h1 { color:#fff;}
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="5" cols="50"></textarea>
In the above code, I am able to enter only 5 times, then after that it shows an error message. It means no extra row add on enter and not to set character limit. if textarea field with text and tried to enter character 2nd or 3rd line thenor last line then it remove character automatically

set a timer between requests from html inputs by withSuccessHandler and onSuccess

I have the problem in html page.
User enters data in html inputs and clicks enter.
After this it must start checking by the function "keyPressFunction" throw withSuccessHandler(onSuccess) to the Google-apps script function "searchData" in 3 tables on spreadsheet and result must return to var "findData" with true/false. If it true, then focus goes to next input. After third input the data writes to table.
But answer from apps-script returns slowly, near 5 seconds, but the focus is already goes out, when the data is really uncorrect. Can you help me this timer between requests?
For understanding the test project is here https://docs.google.com/spreadsheets/d/1FqUmJcTipwKX9Q5m-4dlmXIChp5k1Z98xR2m42GpIT0/edit#gid=0
and last deployed link of web app is here https://script.google.com/a/fmlogistic.com/macros/s/AKfycbwAcfIVGrbcu24t_6OxtR2gvltG3ojbh1_pNxLed1O8/dev
<script>
const inputs = document.querySelector('.dws-input');
const formControl = document.querySelectorAll('.form-control');
let findData;
let curInpID;
let firstValid, secValid, thirdValid, allValid;
formControl[0].focus();
function keyPressFunction(ev) {
let userInfo = {};
userInfo.login = document.getElementById("tLogin").value;
userInfo.table = document.getElementById("tTable").value;
userInfo.order = document.getElementById("tOrder").value;
let inputData = ev.target.value
let btnReset = document.getElementById("del");
if (ev.code !== 'Enter') return;
if (ev.target.classList.contains("is-valid")) ev.target.classList.remove("is-valid");
if (ev.target.classList.contains("is-invalid")) ev.target.classList.remove("is-invalid");
curInpID = ev.target.id;
google.script.run.withSuccessHandler(onSuccess).searchData(inputData, curInpID);
//the true/false returns here in findData:
console.log(findData);
if (!findData) {
ev.target.classList.add("is-invalid");
ev.target.focus();
return;
} else {
ev.target.classList.add("is-valid");
};
btnReset.disabled = (!firstValid == true);
allValid = (firstValid == true && secValid == true && thirdValid == true) ? true : false;
for (const i of formControl) {
if (i.value === '') {
i.nextElementSibling.focus();
break;
}
}
if (allValid){
google.script.run.userClicked(userInfo);
document.getElementById("tTable").value = '';
document.getElementById("tOrder").value = '';
secValid = false;
thirdValid = false;
document.getElementById("tTable").focus();
}
}
function onSuccess(_findData) {
findData = _findData;
if (!firstValid) firstValid = (findData && curInpID == "tLogin") ? true : false;
if (!secValid) secValid = (findData && firstValid && curInpID == "tTable") ? true : false;
if (!thirdValid) thirdValid = (findData && firstValid && secValid && curInpID == "tOrder") ? true : false;
allValid = (firstValid && secValid && thirdValid) ? true : false;
}
inputs.addEventListener('keydown', keyPressFunction);
</script>
<!doctype html>
<html lang="en">
<head>
<title>CLR: PACKING</title>
<meta charset = "UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name= "username" placeholder= "Login:" autofocus >
<label for="tLogin">Login:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name= "text" placeholder= "Table:" >
<label for="tTable">Table:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name= "text" placeholder= "Order:" >
<label for="tOrder">Order:</label>
</div>
</div>
</form>
</div>
<?!= include("index-js"); ?>
</body>
</html>
at Apps script I have next script:
const url = SpreadsheetApp.getActiveSpreadsheet().getUrl();
let ss = SpreadsheetApp.openByUrl(url);
let sheetTo = ss.getSheetByName("#sistem");
let sheetIn = ss.getSheetByName("#packing");
function doGet(e){
var htmlServ = HtmlService.createTemplateFromFile("index");
return htmlServ.evaluate();
}
function userClicked(userInfo){
sheetIn.appendRow([userInfo.login, userInfo.table, userInfo.order, new Date()]);
Logger.login(userInfo.name + "clicked the button");
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function searchData(inputData, curInpID){
var result;
var lrLogins = sheetTo.getRange("A:A").getValues().filter(String).length;
var arrLogins = sheetTo.getRange(1, 1, lrLogins, 1).getValues().flat();
var lrTMPLORDS = sheetTo.getRange("K:K").getValues().filter(String).length;
var curTMPLORDS = sheetTo.getRange(1, 11, lrTMPLORDS, 1).getValues();
var lrTABLES = sheetTo.getRange("R:R").getValues().filter(String).length;
var curTABLES = sheetTo.getRange(1, 18, lrTABLES, 1).getValues().flat();
if (curInpID == "tLogin"){
result = (arrLogins.indexOf(inputData) !== -1) ? true : false;
}
else if (curInpID == "tTable"){
result = (curTABLES.indexOf(inputData) !== -1) ? true : false;
}
else if (curInpID == "tOrder"){
for (i = 0 ; i < curTMPLORDS.length; i ++){
var regexstring = curTMPLORDS[i];
var regexp = new RegExp(regexstring, "i");
var result = regexp.test(inputData);
if (result) break;
}
}
return result;
}
Issue:
If I understand you correctly, you want to avoid the keydown events to execute keyPressFunction while the server-side function searchData hasn't still returned the data.
Solution:
If that's the case, I'd suggest you to use removeEventListener at the start of the keyPressFunction (in order to avoid successive keydown event to trigger more executions of this function), and add it again via addEventListener when executing you success handler function (onSuccess).
It could be something along the following lines:
function keyPressFunction(ev) {
inputs.removeEventListener('keydown', keyPressFunction);
// ... REST OF YOUR FUNCTION
}
function onSuccess(_findData) {
// ... REST OF YOUR FUNCTION
inputs.addEventListener('keydown', keyPressFunction);
}
Update:
keyPressFunction finishes execution without calling the server-function searchData if the pressed key is not Enter. Since the event will only be reactivated after searchData returns and onSuccess runs, it will not be reactivated if the pressed key is not Enter. Because of this, keyPressFunction will only run once (if the pressed key is not Enter).
In order to avoid this, move the removeEventListener line to just before calling searchData:
function keyPressFunction(ev) {
// ... REST OF YOUR FUNCTION
inputs.removeEventListener('keydown', keyPressFunction);
google.script.run.withSuccessHandler(onSuccess).searchData(inputData, curInpID);
}
Sidenote: Please note that everything that is written in keyPressFunction after calling searchData will never be executed, since the execution will be moved to the failure or success handlers (onSuccess in your case). So move that on top of the mentioned line (starting with google.script.run) if you want it to run.
Reference:
removeEventListener

HTML input with decimal format 999,99

When I introduce 3 integer I cannot introduce nor decimal separator neither decimals until I delete some digit.
It must be in keypress and I tested with regex and everything I know aboy javascript and JQuery.
Thank you very much.
$('#calculator-input').keypress(function (event) {
var $this = $(this);
if ((event.which != 44 || $this.val().indexOf(',') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 44) && (text.indexOf(',') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf(',')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf(',') + 3));
}
}, 1);
}
if ((text.indexOf(',') != -1) &&
(text.substring(text.indexOf(',')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
var calculatorInput = $('#calculator-input').val().split(",");
var integers = parseInt(calculatorInput[0], 10);
var decimals = parseInt(calculatorInput[1], 10);
if(calculatorInput[0].length >= 3) {
return false;
}
});
As far as I understood your question, you want to format the number in the input field. But how about this solution?
document.getElementById("decimal-input").onkeyup = function() {
var digits = this.value.match(/\d/g);
if(digits) {
digits = +digits.join("");
this.value = digits.toLocaleString();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">
</head>
<body>
<input type="text" id="decimal-input">
</body>
</html>
I'll recommend to use the keyup event but you can replace it with keypress event too. I haven't added the validation but try it out and see if it works for you.

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

Allow only numeric with dot separated values in textbox

A text box must allow to enter only numbers from 0 to 9 and the maximum length of the field is 5 and the text box must accept values upto 99.99 only.
HTML INPUT TAG
<input id="input" onblur="validate(this)"/>
JAVASCRIPT
function validate(inputField)
{
if(inputField.value.length > 5)
alert("Field should be less than 5 in length");
else if(parseFloat(inputField.value) > 99.99)
alert("value should be less than 99.99");
else
this.form.submit();
}
This got the code to work:
<HTML>
<HEAD>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<SCRIPT language=Javascript>
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
$(document).ready(function ()
{
$('#Percentage1').keyup(function (event)
{
var currentValue = $(this).val();
var length = currentValue.length;
if (length == 2)
{
$(this).val(currentValue + ".");
}
else if (length == 3)
{
$(this).val(currentValue + "");
}
});
});
</SCRIPT>
</HEAD>
<BODY>
<input class="user-reg-input fl" type="text" name="Percentage[]" id="Percentage1" value="" onpaste="return false"
onkeypress="return isNumberKey(event)" maxlength="5" />
</BODY>
</HTML>