How to valid Numeric values onkeypress - javascript

I have this simple HTML document
<input type="text" id="my_text" onkeypress="valid_numbers(event);" size="30"/>
<script type="javascript">
function valid_numbers(e)
{
var key=e.which || e.KeyCode;
if ( key >=48 && key <= 57)
// to check whether pressed key is number or not
return true;
else return false;
}
</script>
What I want is:
onkeypress of my_text if the pressed key is number allow otherwise deny writing of the character.
But the above code doesn't work, my_text element accept any character, what is wrong with the above code ?!..
Help Please!..

I think the easy way to do this would be:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' />
But the problem comes up when you paste some text then HTML5's number type input may be a better choice:
<input type="number" />
BTW you can find better suggestions if you search the SO like this.

Some very complex answers, but it can be as simple as using a regular expression to return the result of checking if the input was a number or not:
<input onkeypress="return /\d/.test(String.fromCharCode(event.keyCode || event.which))">
Note that this will not stop entering of non-digit characters by pasting, dragging and dropping or script.

var input = document.getElementById('my_text');
input.onkeydown = function(e) {
var k = e.which;
if ( (k < 48 || k > 57) && (k < 96 || k > 105) && k!=8) {
e.preventDefault();
return false;
}
};
and
<input type="text" id="my_text" size="30"/>

Allows only [0-9] number, numpad number, arrow, BackSpace, Tab, Del as wel as Ctrl + C, Ctrl + V, Ctrl + A.
Allow only one dot.
Remove if last char is dot on a blur event.
element.on('keydown', function(e) {
var arrowsKeyCodes = [37, 38, 39, 40];
var numPadNumberKeyCodes = [96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
var dots = [110, 190];
var tabBackDel = [8, 9, 46];
var acv = [65, 67, 86];
// Allow only one dot.
if (e.target.value.indexOf('.') !== -1 && dots.indexOf(e.keyCode) !== -1) {
event.preventDefault();
}
// allow only [0-9] number, numpad number, arrow, BackSpace, Tab, Del
// Ctrl + C, Ctrl + V, Ctrl + A
if (
(e.keyCode < 48 &&
arrowsKeyCodes.indexOf(e.keyCode) === -1 || e.keyCode > 57 &&
numPadNumberKeyCodes.indexOf(e.keyCode) === -1 &&
dots.indexOf(e.keyCode) === -1
) &&
tabBackDel.indexOf(e.keyCode) === -1 &&
(e.ctrlKey === false || e.ctrlKey === true && acv.indexOf(e.keyCode) === -1)
) {
e.preventDefault();
}
});
element.on('blur', function(e) {
var value = e.target.value;
if (value.substring(value.length - 1) === '.')
e.target.value = value.substring(0, value.length - 1)
});

Have not tried this out, but you can use parseInt in your function to check like:
var t = document.getElementById("my_test").value;
if (parseInt(t) == 'NaN') {
// not a number
}

<html>
<body>
<input id="edValue" type="text" onKeyPress="edValueKeyPress()" onKeyUp="edValueKeyPress()"><br>
</body>
<script>
function edValueKeyPress()
{
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
if ( s >=48 && s <= 57)
// to check whether pressed key is number or not
return true;
else return false;
}
</script>
</html>
Use this tested code.it's help you.

You can Simply use JavaScript or HTML5 to execute this
JavaScript:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
HTML 5 (does not require JavaScript, and also does not behave in standard way in many modern browsers.)
<input type="number">
FIDDLE
More on this may look here.

Related

How to restrict just numbers input in input number in Firefox?

In Firefox you can enter letters, they show in the screen but not in the js
code, about the value. I would like just restrict that the user can put in letters in the input field. Just restrict it to numbers.
https://jsfiddle.net/j5fv4htp/1/
<input step="0.1" class="number" name="SupplyAirFlow" value="" pattern=".{1,}" type="number">
document.querySelector("input.number").onkeydown = function() {
console.log("value: ", this.value);
};
If you want only numbers in the input use:
document.getElementsByClassName('number')[0].addEventListener('keydown', function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (!( [8, 9, 13, 27, 46, 110, 190].indexOf(key) !== -1 ||
(key == 65 && ( e.ctrlKey || e.metaKey ) ) ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) ||
(key >= 96 && key <= 105)
)) e.preventDefault();
});

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

How to add user input at caret position?

I am facing a weird issue regarding a textbox after using validation for preventing special characters.Lets say I enter some text in it.Now if I change the caret position in between the already entered text and try to add text there, the caret automatically jumps to the end of the text.
Any workaround for this?
Note:- I am using IE 11.
Textbox :-
<div class="form-group">
<label data-i18n="rpt_name"></label>
<span class="required">*</span>
<input type="text" class="form-control" id="subNameID">
</div>
The source of error is validation for avoiding special characters.
$('#subNameID').bind('keypress', function (e) {
if ($('#subNameID').val().length == 0) {
var k = e.which;
var ok = k >= 65 && k <= 90 || // A-Z
k >= 97 && k <= 122 || // a-z
k >= 48 && k <= 57; // 0-9
if (!ok) {
e.preventDefault();
}
}
})
Also tried using below solution but gives the same issue.
$("#subNameID").on("keypress keyup paste", function (e) {
if (e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 8)
return true;
this.value = this.value.replace(/[^a-zA-Z0-9\-\._\s]/g, '');
});

Backspace does not delete dashes

I'm attempting to create a field that adds dashes to a number so that it takes the form of a telephone number. It adds the dashes, but if the user tries to backspace their way back to the beginning it does not allow the user to delete the dash. Well, it deletes it but then the dash re-populates.
The JavaScript that allows only numbers with exceptions that I'm currently using:
function forceNumber(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if((keyCode < 48 || keyCode > 58) && keyCode != 8 && keyCode != 188 && keyCode != 189) {
return false;
}
return true;
}
The js that creates the dashes:
function addDashes(n){
n = n.replace(/,/g, "");
var s=n.split('.')[1];
(s) ? s="."+s : s="";
n=n.split('.')[0];
if(n.length == 3 || n.length == 7 || n.length == 13){
s="-"
}
return n+s;
}
And the PHP/HTML call (I'm not sure if the right-align may be the cause):
<p id="phone_number">
<label for="phone_number"><?php _e('Phone Number','mydomain') ?><br />
<input type="text" name="phone_number" id="phone_number" class="input" size="25" style="text-align:right" onkeypress="return forceNumber(event);" onkeyup="this.value=addDashes(this.value);"/>
</p>
Simple change in your html I changed this line to add the event information:
<input ... onkeyup="this.value=addDashes(this.value, event);"/>
In the addDashes function I changed the signature to take the event and added an if to handle the backspace
function addDashes(n, ev){
// ...
}
However I noticed a more fundamental problem with your method. If somebody inserts a character it'll break the logic. So if the text is 123-45, and I paste the number 6 between 2 & 3, the result will be 1263-45.
Here's a different approach to addDashes that just checks the whole string each time.
function addDashes(n, ev){
n = n.replace(/[^\d]/g, "");
if (n.length > 3) {
n = insert(n, 3, '-');
if (n.length > 7) {
n = insert(n, 7, '-');
if (n.length > 13) {
n = insert(n, 13, '-');
}
}
}
return n;
}
function insert(s1, index, s2) {
return s1.substring(0, index) + s2 + s1.substring(index);
}
Another variation of addDashes that avoids the conditionals in favor of an unwieldy regex.
function addDashes(n, ev){
n = n.replace(/[^\d]/g, "")
.replace(/(\d{3}(?=\d))((\d{3}(?=\d))|(\d{0,3}$))((\d{4}(?=\d))|(\d{0,4}$))/,
function(m, $1, $2, $3, $4, $5, $6, $7) {
return (($1) ? $1 + '-' : m) +
(($3) ? $3 + '-' : $4) +
(($6) ? $6 + '-' : $7);
});
return n;
}
You can also adjust the second method to do different formatting without having to worry about string lengths. For example you can change the replace function to return in the format (ddd) ddd-dddd
return (($1) ? '(' + $1 + ') ' : m) +
(($3) ? $3 + '-' : $4) +
(($6) ? $6 + '-' : $7);
if(n.length == 3 || n.length == 7 || n.length == 13){
s="-"
}
When you backspace the dash, the length is 3 again, so the dash gets added. You are going to have to check if the last key the user pressed is backspace, like
var lastKeyIsBackspace;
if(!lastKeyIsBackspace && (n.length == 3 || n.length == 7 || n.length == 13)){
s="-";
}
Then, check if the key was backspace in your key handler:
function forceNumber(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if((keyCode < 48 || keyCode > 58) && keyCode != 8 && keyCode != 188 && keyCode != 189) {
return false;
}
// check if the key was backspace (key code 8)
if (keyCode == 8) lastKeyIsBackspace = true;
else lasyKeyIsBackspace = false;
return true;
}
Here is how I would do it. One thing I'm doing is removing the javascript from the actual dom elements. So your input would look like this:
<input type="text" name="phone_number" id="phone_number" class="input" size="25" style="text-align:right" />
UPDATE: since I noticed you have jquery sourced and you prefer the dashes to show before the 4th and 7th digits are typed. the following should be good for you:
http://jsfiddle.net/3e9XE/8/
$(document).ready(function () {
$("#phone_number").on("keypress", function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if ((keyCode < 48 || keyCode > 58) && keyCode != 8 && keyCode != 188 && keyCode != 189) {
e.preventDefault();
}
})
.on("keyup", function (e) {
var str = this.value;
if (e.keyCode == 8) {
if ("-" == str.charAt(str.length - 1)) {
str = str.substring(0, str.length - 1);
}
} else {
str = str.replace(/\D/g, '')
.replace(/(\d{3})(.*)/, "$1-$2")
.replace(/(\d{3}-\d{3})(.*)/, "$1-$2");
}
this.value = str;
});
});

Detect numbers or letters with jQuery/JavaScript?

I want to use an if-statement to run code only if the user types in a letter or a number.
I could use
if (event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || ...) {
// run code
}
Is there an easier way to do this? Maybe some keycodes don't work in all web browsers?
If you want to check a range of letters you can use greater than and less than:
if (event.keyCode >= 48 && event.keyCode <= 57) {
alert('input was 0-9');
}
if (event.keyCode >= 65 && event.keyCode <= 90) {
alert('input was a-z');
}
For a more dynamic check, use a regular expression:
const input = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9-_ ]/.test(input)) {
alert('input was a letter, number, hyphen, underscore or space');
}
See the MDC documentation for the keyCode property, which explains the difference between that and the which property and which events they apply to.
Use event.key and modern JS!
No number codes anymore. You can check key directly.
const key = event.key.toLowerCase();
if (key.length !== 1) {
return;
}
const isLetter = (key >= 'a' && key <= 'z');
const isNumber = (key >= '0' && key <= '9');
if (isLetter || isNumber) {
// Do something
}
You could also use a simple regex. ^$ ensures 1 char, i ignores case
/^[a-z0-9]$/i.test(event.key)
or individually:
const isLetter = /^[a-z]$/i.test(event.key)
const isNumber = /^[0-9]$/i.test(event.key)
First, if you're doing this, make sure it's in the keypress event, which is the only event for which you can reliably obtain information about the character the user has typed. Then I'd use the approach Andy E suggested:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
alert("Letter or number typed");
}
};
If you want to check for backspace, I'd use the keydown event instead and check for a keyCode of 8 because several browsers (including Chrome) do not fire a keypress event for the backspace key.
if (event.keyCode >= 48 && event.keyCode <= 90) {
// the key pressed was alphanumeric
}
For numeric values:
function validNumeric() {
var charCode = event.which ? event.which : event.keyCode;
var isNumber = charCode >= 48 && charCode <= 57;
if (isNumber) {
return true;
} else {
return false;
}
}
Here, 48 to 57 is the range of numeric values.
For alphabetic values:
function validAlphabetic() {
var charCode = event.which ? event.which : event.keyCode;
var isCapitalAlphabet = charCode >= 65 && charCode <= 90;
var isSmallAlphabet = charCode >= 97 && charCode <= 122;
if (isCapitalAlphabet || isSmallAlphabet) {
return true;
} else {
return false;
}
}
Here, 65 to 90 is the range for capital alphabets (A-Z), and
97 to 122 is the range for small alphabets (a-z).
As #Gibolt said, you should use event.key.
Because charCode, keyCode and which are being deprecated.
To detect letters & numbers when using <input> or <textarea> you can use input event.
This event fires when <input> or <textarea> value changes so there is no need to worry about keys like Alt, Shift, arrows etc. Even more - if you use mouse to cut part of the text the event fires as well.
var element = document.getElementById('search');
element.addEventListener('input',function(e){
console.log(element.value);
});
<input id="search" type="text" placeholder="Search" autocomplete="off">
Simply you can add your Html forms in the input field like this:
...onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"
You don't need any function. This Validation works only with the email field. Don't use naming or number. To use number, remove email regular expression like this:
...onkeypress ="return /[a-z ]/i.test(event.key)" required accesskey="4"
For number only:
...onkeypress ="return /[0-9]/i.test(event.key)" required accesskey="4"
Don't forget, to add for each input fields their own value.
<div class="form-group">
<input type="Email" class="form-control " id="EMAILADDRESS" name="EMAILADDRESS" placeholder="Email Address" autocomplete="false" onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"/>
</div>
$('#phone').on('keydown', function(e) {
let key = e.charCode || e.keyCode || 0;
// 32 = space - border of visible and non visible characters - allows us to backspace and use arrows etc
// 127 - delete
if (key > 32 && (key < 48 || key > 58) && key !== 127) {
e.preventDefault();
return false;
}
});
modified answer of #user4584103, allows us to remove characters, and navigate in input box and filter out every not number character
You can also use charCode with onKeyPress event:
if (event.charCode > 57 || event.charCode < 48) {
itsNotANumber();
} else {
itsANumber();
}
number validation, works fine for me
$(document).ready(function () {
$('.TxtPhone').keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
// only numbers
if (key < 48 || key > 58) {
return false;
}
});
});
Accept numbers or letters with JavaScript by Dynamic Process using regular expression.
Add onkeypress event for specific control
onkeypress="javascript:return isNumber(event)"
function numOnly(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
function Alphanum(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
Use $.isNumeric(value); return type is boolean
$(document).ready(function () {
return $.isNumeric(event.keyCode);
});
A very simple, but useful method to try (i needed on a keyup event, letters only),
use console.log() to check, typeOfKey is a string so you can compare. typeOfKey is either (Digit or Key)
let typeOfKey = e.code.slice(0,-1)
if(typeOfKey === 'Key'){
console.log(typeOfKey)
}

Categories

Resources