jquery - Numeric Only Text Field - javascript

I found this very short clean code to only allow numeric chars in a text field. Currently it only covers numbers 0-9 and backspace and delete. I wanted it to also include decimal/period, so I have been fighting with this to simply include keycode 110 and/or 190. I can not get it to work. Can anyone see what I am doing wrong?
$(document).ready(function() {
$('input.numberinput').bind('keypress', function(e) {
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) ) || (e.which!=110) ? false : true ;
});
});
jsfiddle here: http://jsfiddle.net/justmelat/EN8pT/
html
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber1" id="txtNumber1" value="" class="numberinput" />
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber2" id="txtNumber2" value="" class="numberinput" />
</div>

Try:
$(document).ready(function () {
$('input.numberinput').bind('keypress', function (e) {
return !(e.which != 8 && e.which != 0 &&
(e.which < 48 || e.which > 57) && e.which != 46);
});
});​
JsFiddle: http://jsfiddle.net/EN8pT/1/

With the above answer you can still do 0.23.12.33 which is not a valid number.
http://www.texotela.co.uk/code/jquery/numeric/ is a great little lightweight plugin that I have used a lot. It takes the pain out of the above.

$("#input").keydown(function(event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
// Allow: backspace, delete, tab, escape, and enter
if ( key == 46 || key == 8 || key == 9 || key == 27 || key == 13 || key == 110 || key == 190 ||
// Allow: Ctrl+A
(key == 65 && theEvent.ctrlKey === true) ||
// Allow: home, end, left, right
(key >= 35 && key <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (theEvent.shiftKey || (key < 48 || key > 57) && (key < 96 || key > 105 )) {
theEvent.preventDefault();
}
}
});
with keycode 110 and 190

Related

how to restrict zero at position 0

$('input#abc').keypress(function(e){
if (this.value.length == 0 && e.which == 48 || this.value.length == 0 && e.which == 46 ){
//console.log(JSON.stringify(this.value.length[0]);
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type="text" id="abc" />
In the above snippet, zero and dot can't be entered when the length ==0. In this scenario it is working.
But when we type other than zero and dot, return to the first position, and enter zero or dot it is accepted.
I want to disallow zero and dot at any time as the first character.
That is because you are checking the condition only when your textarea length is zero. Instead, check for the textarea cursor position. If it is at zero and user enters invalid character, return false. Basically, replace your if condition from
if (this.value.length == 0 && e.which == 48 || this.value.length == 0 && e.which == 46 )
to
if (this.selectionStart == 0 && e.which == 48 || this.selectionStart == 0 && e.which == 46 )
and if you want it to be more concise, you can do something (as recommended by #0x90) like
if (this.selectionStart == 0 && (e.which == 48 || e.which == 46 ))
You can check selectionStart to see cursor position
$('input#abc').keypress(function(e){
if (e.currentTarget.selectionStart === 0){
if(e.which == 48 || e.which == 46 ) {
return false;
}
}
});
https://caniuse.com/#search=selectionStart

Input should allow numbers and dash character

I have written jquery for allowing numbers and dash - from being entered
$('.no-special-characters').keydown(function(e){
if (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode == 45) {
return true;
} else {
return false;
}
});
It does not work accordingly. It allows only numbers to be accepted.
try this code
$('.no-special-characters').keydown(function(e) {
if (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode == 189) {
return true;
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="no-special-characters">
Try this
Updated with backspace support
Allow the keycode of 189
$('.no-special-characters').keydown(function(e) {
var key = e.keyCode|e.which;
console.log(key) //check the key value in your console.log
if (key >= 48 && key <= 57 || key == 45 || key == 189 ||key == 8){
return true;
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="no-special-characters">
Here you go with one more solution
$('.no-special-characters').keydown(function(e){
if ((e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode == 189) {
return true;
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="no-special-characters" type="text" />
Usually combine the keyCode from 48 to 57 & then the next keyCode condition.
Hope this will help you.
e.keyCode = 109 is '-' on numpad
e.keyCode = 189 is '-' in alphabate keybord key on chrome
e.keyCode = 173 is '-' in alphabate keyboard key on firefox & on chrome 173 keycord is Mute On|Off
Source
Maybe this helps you, because using only e.keyCode == 189 (as some answers say) wont work in Firefox.
You can see, what keyCode your key presses return here: Link
Edit: You can also use regular expressions. Then there is no need to add keyCodes for different browsers:
$('.no-special-characters').keypress(function(e){
var txt = String.fromCharCode(e.which)
var pattern = /^[0-9\-]+$/;
if (!(pattern.test(txt) || e.keyCode == 8)){
return false;
}
})
JSFiddle

How can I create input fields like on any Shopify checkout page?

I would like to create 3 input fields just like the ones on any Shopify checkout page.
Here are the functions for the input fields:
making spaces every 4 digits in the credit card number input field; number-only field; limiting it to 16 characters
creating a slash in after 2 digits for the expiration date field; limiting it to 8 characters; number-only field
This one would allows the user to do 2 things:
Write a number from 2-9, which automatically writes a slash afterwards.
It should look like this.
Write either 10, 11, or 12, which automatically writes a slash afterwards.
It should look like this.
See how it writes a slash automatically right after the second number? It only does that if you type in "/" or a second number for the month.
Here is what I'm playing with:
/*$('#number').on('keypress',function(){
var val = this.value;
var firstVal = val.slice(0,2);
var secondVal = val.slice(2,6);
var finalVal = firstVal+"/"+secondVal;
console.log(finalVal);
this.value = finalVal;
}); */
$('#number').on('keypress', function() {
if (this.value.length >= 2) {
this.value = this.value.slice(0, 2) + '/' + this.value.slice(3, this.value.length)
}
});
$(document).ready(function() {
$("#number").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl/cmd+A
(e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: Ctrl/cmd+C
(e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: Ctrl/cmd+X
(e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<input type="text" id="number" maxlength="7" placeholder="MM/YY" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
But the problem I'm having here is that you can't even type a slash.
Thanks in advance,
Josiah

jQuery prevent writing letters and change comma to dot

I have tried to modify this code but it just wont work...probably some small mistake but i can't debug it :(
// replace , with . and block writing letters
$(document).on("keydown", ".amount", function () {
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
};
This is original code and it doesn't work on dynamic content
that is why i want to modify it!
How about just calling your ForceNumericOnly method when the user clicks into an input with .amount?
$(document).on('focus', '.amount', function(){
$(this).ForceNumericOnly();
});
https://jsfiddle.net/daveSalomon/r5n8xuhx/5/
You could (should) optimise it so it doesn't add the keydown handler again if it's already run the ForceNumericOnly code... something like:
$.fn.ForceNumericOnly = function() {
return this.each(function() {
if($(this).data('forceNumberOnly'){ return; }
$(this).data('forceNumberOnly',true);
...
});
};
https://jsfiddle.net/daveSalomon/r5n8xuhx/6/
There's no JS required - just use a number input:
<input class="amount" type="number">

using jQuery/javascript to restrict price field input

I found the following jQuery code on the internet, but I soon found that it had a deficiency in that it dit not accept a decimal point (ascii code 46) - even though the code appears to allow it.
Currently, I cannot enter prices like 1.23, since the the period is ignored and I get 123 instead.
Can anyone spot whty this is not working?
// Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};
I am using the plugin like this:
$(function(){
$('#price_field').ForceNumericOnly();
});
The other users have pretty much answered your question already, but I wanted to provide you with this link.
http://unixpapa.com/js/key.html
I found it quite useful when dealing with keyboard events and making them cross-browser compatible.
I hope this helps.
Just add the . (code 190 and 110) to the checks:
// Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 190 || // normal .
key == 110 || // keypad .
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};
You should add the key code 190 to accept "."
// Numeric only control handler
$.fn.ForceNumericOnly = function() {
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow dot, backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 190 ||
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};
You need to include 190 and 110 for both decimal points.
// Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 190 || //add this line. 190 is the keycode for a period
key == 110 || //and this line. 110 is the keycode for a decimal
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};

Categories

Resources