I've limited the input field to only numbers through js but am not sure how to also allow decimals...
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Thank you in advance!
Answer:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
return true;
}
Adding the charCode 46 worked perfectly (keypress value). 190 and 110 did nothing.
Thanks for your help all!
Codes depend on which event you're listening to, an easy way to find what you want is by using the JavaScript Event KeyCode Test Page here with test input, e.g. for a full stop (the . left of right shift) you have
onKeyDown onKeyPress onKeyUp
event.keyCode 190 46 190
event.charCode 0 46 0
event.which 190 46 190
and for the . on the numeric pad it is
onKeyDown onKeyPress onKeyUp
event.keyCode 110 46 110
event.charCode 0 46 0
event.which 110 46 110
As you can see, it is most uniform to check with onKeyPress with charCode which is it's unicode number; String.fromCharCode(46); // ".".
There is a full list on the MDN page for KeyboardEvent where it is also stated
Note: Web developers shouldn't use keycode attribute of printable keys in keydown and keyup event handlers. As described above, keycode is not usable for checking character which will be inputted especially when Shift key or AltGr key is pressed. When web developers implement shortcut key handler, keypress event is better event for that purpose on Gecko at least. See Gecko Keypress Event for the detail.
You can observe the strange effects of using AltGr or Shift on keyCode with the key of choice in the test page I linked to as well.
With HTML5, the input element got a new attribute: pattern. You can specify a regular expression that is validated by the browser before submitting the form.
<input type="text" pattern="([0-9]+\.)?[0-9]+" />
It is not widely supported yet, though.
The pattern attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome.
(w3schools)
Disclaimer: the expression is weak, go build a better one :)
Assuming you're using on key down or up:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || (charCode > 57 && charCode != 190 && charCode != 110)))
return false;
return true;
}
110 is decimal point, 190 is period
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Heres a fiddle with some test cases
<asp:TextBox ID="txt" onkeypress="return isDecimalKey(event,this)" runat="server">
function isDecimalKey(evt,obj)
{
var charCode = (evt.which) ? evt.which : event.keyCode
var value = obj.value;
var dotcontains = value.indexOf(".") != -1;
if (dotcontains)
if (charCode == 46) return false;
if (charCode == 46) return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
}
In MVC
#Html.TextBoxFor(m => m.fieldName, new { htmlAttributes = new { #class = "form-
control forDecimal" }})
$(document).on("keypress", ".forDecimal", function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
var value = $(this).val();
var dotcontains = value.indexOf(".") != -1;
if (dotcontains)
if (charCode == 46) return false;
if (charCode == 46) return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
});
Related
Here is my code
document.addEventListener('keyup', logKey);
function logKey($event) {
var charCode = $event.keyCode;
if(charCode > 31 && (charCode < 48 || charCode > 57 || charCode > 107 || charCode > 219 || charCode > 221) && charCode != 40 && charCode != 32 && charCode != 38 && charCode != 41 && (charCode < 43 || charCode > 46)){
var inputElement = document.getElementById("input");
inputElement.focus();
inputElement.value = inputElement.value + $event.key;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="text" id="input">
On page load, if the user starts typing the focus is focusing the input but it's not allowing the user to enter the characters typed. As of now, the focus is working but it's not working as expected when the user typing continuously.
Please help me out on this. Any help will be appreciated.
The issue in the code in the question is because you're appending the character which was just typed in the input back in to the input, effectively duplicating that character.
Given your statement in the comments of your intended goal:
when the user starts typing only I need to focus on the input
You can attach a keypress event handler to the document which sets focus on the input as soon as a character is typed:
$(document).on('keypress', e => {
var charCode = e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode > 107 || charCode > 219 || charCode > 221) && charCode != 40 && charCode != 32 && charCode != 38 && charCode != 41 && (charCode < 43 || charCode > 46)) {
$('#input').focus();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input">
I would also suggest you review your if condition, as the 3 conditions following > 57 are redundant.
charCode > 57 || charCode > 107 || charCode > 219 || charCode > 221
I have implemented the below javascript method to restrict typing special characters except space, backspace, dot, hyphen and underscore but in a textbox and called this method in the onkeypress event of textbox.
The reason I have posted it here is it is working fine in laptop or pc but the validation is not working on tablet.
Can anyone tell me the reason for this?
function NoSpecialCharacters(evt) {
//this method allows alphabets numbers and some special
//characters like space, backspace, dot, hyphen and underscore
var keyCode = (evt.which) ? evt.which : event.keyCode
if ((keyCode >= 33 && keyCode <= 44) || keyCode == 47 || (keyCode >= 58 && keyCode <= 64) ||
(keyCode >= 123 && keyCode <= 126) || (keyCode >= 91 && keyCode <= 94) || keyCode == 96) {
return false;
}
return true;
}
I am working on this code in which it checks validation on numeric characters. In the same way, I want validation on alpha-only characters. I have tried many symbols but failed to succeed.
if (/\D/.test(x))
{
alert("Please only enter numeric characters (Allowed input:0-9)")
return false;
}
What changes are required in this code for alpha-only validation.
Using .test()
If you want to keep with the .test() method, I believe that the below would work for you.
Identify if the input is numeric.
if (/^[a-zA-Z]+$/.test(x))
{
alert("Please only enter numeric characters (Allowed input:0-9)")
return false;
}
Identify if the input contains a-z/A-Z
if (!/^[a-zA-Z]+$/.test(x))
{
alert("Please only enter letters (Allowed input: a-z, A-Z)")
return false;
}
Fiddle
Not Using .test()
You can also set up functions that look for the value during the onkeypress event
Allow only numerical characters to be entered in select fields || onkeypress="return isNumberKey(event)"
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode > 31 && (charCode < 48 || charCode > 57)){return false;}
return true;
}
Allow only alpha characters to be entered in select fields || onkeypress="return isAlphaKey(event)"
function isAlphaKey(evt)
{
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
if(charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)){return false;}
return true;
}
I have one text box in which, user should enter only alphanumeric characters and non-text key presses should be allowed like backspace, arrow keys, etc . Also, it should also work on all major browsers (like Mozilla Firefox).
I have tried few examples which allowed to me enter only alphanumeric characters but backspace don't work with this below example in Mozilla Firefox.
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
You can add [\b] to match and allow backspace.
Code:
var regex = new RegExp("^[a-zA-Z0-9\b]+$");
Demo: http://jsfiddle.net/M3bvN/
UPDATE
Instead of extend your regex you can check if the pressed key is in a list of allowed keys (arrows, home, del, canc) and if so skip the validation.
This not prevent the user to copy/paste not allowed characters. so perform the validation control in the blur event too (and always on server side).
Code:
var keyCode = event.keyCode || event.which
// Don't validate the input if below arrow, delete and backspace keys were pressed
if (keyCode == 8 || (keyCode >= 35 && keyCode <= 40)) { // Left / Up / Right / Down Arrow, Backspace, Delete keys
return;
}
Demo: http://jsfiddle.net/M3bvN/3/
I was working on this for a bit, and this is what I came up with:
var input = $('input[name="whatever"]');
input.bind('keypress', function(e)
{
if ((e.which < 65 || e.which > 122) && (e.which < 48 || e.which > 57))
{
e.preventDefault();
}
});
It only allows numbers and letters, both upper- and lower-case. Note that it also disallows the space bar (that's what was needed for my application).
function lettersOnly(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
((evt.which) ? evt.which : 0));
if (charCode == 8 || charCode == 46 || charCode == 37 || charCode == 39) {
return true;
} else if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
// alert("Enter letters only.");
return false;
}
return true;
}
$('.alphanumeric').bind('keypress', function (e) {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
return ret;
});
This code will Firefox also
This code is responsible for preventing users from entering non-numeric characters such any any ascii except number [0-9]. Works fine in in IE, but not in Firefox and Chrome. Any help and suggestions are highly appreciated.
Thank you
'oKeyPress': function (e) {
e = e || window.event;
var charCode = (navigator.appName == "Netscape") ? e.which : e.keyCode;
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
Use feature detection; not browser detection:
var charCode = e.charCode || e.keyCode;
inside your KeyPress event to get the charcode use this:
return (window.event ? e.keyCode : e.which)
Thank you guys for your suggestions and feedback; I just found out why it did not work on Firefox and chrome before. The reason it was not working was because I was using something like this code from my Code-behind C# code :
this.txtApsId.Attributes.Add("onkeypress", "return (function(e) {var charCode = (navigator.appName == 'Netscape') ? e.which : e.keyCode; return charCode > 31 && (charCode < 48 || charCode > 57); }(event || window.event))");
Thanks