how to restrict zero at position 0 - javascript

$('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

Related

Here is some JavaScript that is supposed to run on the keyup event, but only if the keycode is between 48 and 57. Here is the code [duplicate]

This question already has answers here:
keyCode values for numeric keypad?
(13 answers)
Closed 1 year ago.
$('#cnic1').keydown(function(){
if (event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true) )
return;
if((event.keyCode < 48 || event.keyCode > 57))//0-9
event.preventDefault();
var length = $(this).val().length;
if(length == 5 || length == 13)
$(this).val($(this).val()+'-');
});
My problem is that this code only runs in response to the numbers entered at the top of the keyboard, but does not run in response to numbers entered from the numeric keypad.
I'm thinking the answer must be that the numeric keypad has different keyCode values, but how do I find out what those are?
The numeric keypad does have different keyCode values. The following link gives a full table of keyCodes for your reference:
https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Use this code and press the keys. keycodes will be on console log;
window.onload = function(){
addEventListener("keydown",function(e){
console.log(e.keyCode);
});
}
Change if condition as
if((event.keyCode < 48 || event.keyCode > 57)&&(event.keyCode < 96 || event.keyCode > 105))//0-9
$('#cnic1').keydown(function() {
if (event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true))
return;
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) //0-9
event.preventDefault();
var length = $(this).val().length;
if (length == 5 || length == 13)
$(this).val($(this).val() + '-');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="cnic1">

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

Textbox to accept decimal and negative as well as backspace using Jquery

I am trying to restrict text box to accepts only decimals,integers and also - (negative sign) as well as backspace I tried with below script but its not allowing - sign
$(document).ready(function() {
$('#MainContent_txtAmount').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="MainContent_txtAmount" type="text" />
How can I accepts negative numbers too.
This allows the "-" sign too. Added && event.which != 45 . DEMO FIDDLE
$(document).ready(function () {
$('#MainContent_txtAmount').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8)) && event.which != 45) {
event.preventDefault();
}
var text = $(this).val();
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
});
Find the attached fiddle
sql fiddle demo
"-" has a charCode of 45.
change your condition event.which < 48 || event.which > 57 to
event.which != 45 && (event.which < 48 || event.which > 57)

jquery - Numeric Only Text Field

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

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