In JS I might have this shortcut to trigger an event:
alt + s
I have s from an option. How do I convert the s to the correct number that represent the letter?
In my code I will have something like this, but change the 98 to function that generates the number from a function, with string as input.
if (e.altKey && e.keyCode == 98) {
}
UPDATE
I tried this but it gives the wrong key code:
var _stringToKey = function() {
string = '{{key}}';
return parseInt( string.charCodeAt(0) );
}
{{key}} is replaced by a letter from PHP.
Sidenote
I don't want to rely on yet another JS plugin.
.charCodeAt(n) works on the character. e.keyCode works on the key.
A != a. But the A key does equal the a key.
'a'.toUpperCase().charCodeAt(0) // 65
'a'.charCodeAt(0) // 97
'A'.charCodeAt(0) // 65
'A'.toLowerCase().charCodeAt(0) // 97
Basically, you want:
var _stringToKey = function() {
string = '{{key}}';
return parseInt( string.toUpperCase().charCodeAt(0) );
}
That you are trying exists! It calls Mousetrap.
https://craig.is/killing/mice
Mousetrap.bind(['command+k', 'ctrl+k'], function(e) {
highlight([11, 12, 13, 14]);
return false;
});
Simple and beautiful.
Related
I'm trying to get a response for when visitor uses the keys right and left
<script>
$(document).keypress(function(event) {
key = String.fromCharCode(event.which)
if(key == '37' || key == '39') {
$('main').html('You pressed : ' + key)
event.preventDefault()
}
});
</script>
It's not working. what did work was the line
if(key == 'a')
I used this table to find the code https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Is it because jQuery has different table? or maybe I should load JavaScript as well? then how do I do use the two of them? (jQuery and JavaScript?)?
EDIT:
I think I got it
String.fromCharCode(event.which)
JavaScript can't read strings as numbers? do I need to use different function? I'm new to this can you tell me what to do?
I find for myself that when I go to implement these sorts of "get item from event", that a simple console.log(event) does wonders. I'd start with:
$('body').on('keypress', function(evt){
console.log('Event: ', evt);
});
Then, press the right and left arrow keys and see what happens.
First, an observation: I note that you're comparing the string '37', which is distinct from the integer value 37. The former is two or four bytes (depending on how the JS implementation stores characters), while the latter is one byte. Is that your intention after reading the appropriate APIs?
Second, as a specific suggestion, if you're using jQuery, take advantage of it's normalization routines. In this case, event.which is returning 0, but you can use event.keyCode which is probably what you want to compare:
if ( 37 === event.keyCode ) {
// ...
}
else if ( 39 === event.keyCode ) {
// ....
}
What you want to use is the keydown event. Also, no reason to use the String.fromCharCode, you can just compare the integers. Something like this would work
$(document).keydown(function(event) {
if (event.which == 37 || event.which == 39) {
var key = event.which == 37 ? 'left' : 'right';
$('main').html('You pressed : ' + key)
event.preventDefault()
}
})
We have pin numbers in the following format:
45 674 25 910
Our original requirement was to give the users the ability to enter their pin with or without spaces,
In other words, if the pin is 10 digits without spaces, we would like to accept it as valid input.
Similarly, if the pin is 13 digits (with the three spaces) we would also like to accept the input as valid.
If the digits are less than 10 with or without spaces, or more than 13 with spaces, we would like to throw an error that input is invalid.
The script below satisfied the above requirements:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSearch").click(function () {
var result = true;
if ($('#pin').val().replace(/ /g, '').length == 10) {
result = true;
}
else {
result = false;
alert("Invalid");
return false;
}
return result;
});
});
</script>
However, management has decided to change the requirement to ask that spaces be automatically added while the user is entering the pin numbers.
In other words, users can enter the pin numbers with spaces or they can enter the pin numbers without spaces but that spaces be automatically added while they are typing the pin numbers.
Any ideas how to modify the script above?
Better yet, is there an example that I can modify to meet our requirements?
Using String.prototype.replace()
Note: this code will add space after 2, 3, 2, 3 ..etc chars. you can change the number of chars by edit the code inside map
$("#user-input").on('keyup', function () {
// Helpers
var swap = 4, // Swap between 3 and 4
index = 2; // Spaces indexs 2, 6, 9, 13 .. etc
// This variable contains the same input value with sapces
var niceVal = $(this).val()
.replace("/\s/g", "").split("") // Remove all spaces and convert to array
.map(function (item, i) { // loop throw the array
if (i === 0) {
return item;
}
if (i % index === 0) {
item = item === " "
? item
: " " + item;
index += swap;
swap = swap === 3
? 4
: 3;
}
return item;
}).join(""); // Convert array to string
$(this).val(niceVal); // Update input value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="user-input">
Well with pure JS my approach to the problem could be as follows;
Though i mentioned the keyup event in my comment, it seems the keydown event turns out to be more appropriate since keyup might result a strange behavior when multiple keys are pressed at the same time due to speed typing. I haven't tested this thoroughly so it's just a guidance for you. However, if you discover any buggers i can possibly have a look into it.
Edit: Despite all my efforts I have come to the awareness of the fact that if you want to modify the value of an input element, like in this question, you must set up a logic to utilize both keydown and keyup events in a harmony. This will simplify your logic enormously and would yield a much sturdy code.
OK lets go...
var pin = document.getElementById("PIN"),
pbt = document.getElementById("PBT");
pin.addEventListener("keydown", function(e){
var val = e.target.value,
len = val.length,
lst = val[len-1],
key = e.key;
e.target.value = key === "Backspace" ? len === 4 ||
len === 8 ||
len === 11 ? val.slice(0,-1)
: val
: len === 2 ||
len === 6 ||
len === 9 ? val + "\xa0"
: val;
});
pin.addEventListener("keyup", function(e){
var val = e.target.value,
pix = val.search(/[^0-9\xa0]/); // problem index
e.target.value = ~pix ? val.slice(0, pix) : val
});
pbt.addEventListener("click", function(e){
pin.value.length === 13 ? console.log(pin.value)
: console.log("Please complete the PIN Code");
});
<input id="PIN" value="" placeholder="Enter PIN" maxlength=13 size=13/>
<button id="PBT">Enter PIN</button>
Regular Expression: /^[1-9][0-9]*$/
The regexp works as intended on http://www.phpliveregex.com
My problem is that it doesn't work when implemented with JS, see my code on http://jsfiddle.net/LHHU7
The JS:
$("#mytextbox").on("keypress", function(event) {
var re = /^[1-9][0-9]*$/;
var key = doKey(arguments[0] || window.event);
var char = String.fromCharCode(key);
if (key == 8 || key == 37 || key == 39 || re.test(char)) {
return true;
}
return false;
});
$('#mytextbox').on("paste",function(e)
{
e.preventDefault();
});
function doKey(event) {
var key = event.keyCode | event.charCode;
return key;
}
Test cases expected:
0001 fail
11 11 fail
1000 success
1264 success
5001 success
What's happening with my code:
0001 fail WORKING
11 11 fail WORKING
1000 success NOT WORKING
1264 success WORKING
5001 success NOT WORKING
For some reason 0 won't be entered. I've already tried on chrome, with no success. I've tried changing my RegExp multiple times with no different results. I've also tried different implementations on my code, but still no success.
Please see if you can get it working on my jsfiddle before posting your answers. Thanks!
You're only checking a single character (the latest one) against the regex, when you probably really want to match the content of the textbox + the character. This makes it impossible to enter a zero at all, since it will always be matched against ^[1-9].
Matching the existing textbox value + the character should work better;
if (key == 8 || key == 37 || key == 39 ||
re.test(document.getElementById("mytextbox").value + char)) {
return true;
}
As #Joachim Isaksson mentioned, you are only looking at the last character so your regex is wrong. Update regex to:
var re = /^[0-9]$/;
This will match one number, 0-9.
Edit the Following to your code it works fine DEMO
var testString=$('#mytextbox').val();
if (key == 8 || key == 37 || key == 39 || re.test(testString + char) )
I have a JavaScript function that validates an input field and prevents the user from typing anything that doesn't match the condition. This function is based on event.keyCode.
I'm trying to modify the function to use a RegExp and validates not "per character" but "per whole input" so that it does the same, but with different conditions:
numeric only
allowed decimal "." or ","
Here is the function in its current form, using event.keyCode:
function isNumeric(evt, alertDIVid, alertMsg) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode >= 48 && charCode <= 57) {
document.getElementById(alertDIVid).innerHTML = '';
return true;
}
else {
document.getElementById(alertDIVid).innerHTML = alertMsg;
return false;
}
}
document.getElementById('AMNT').onkeypress = function(event) {
event = event || window.event;
return isNumeric(event, 'numericalert', 'Numeric values only!')
};
In order to do the kind of validation you want, you need to listen to the keyup event instead. This event fires after the field is changed, so that you know the new value of the field. You also need to know the previous value of the field so you can "reset" it if what the user typed turns out to be invalid.
For example:
(function() {
var previousValue = document.getElementById('myInput').value;
var pattern = /^\d*((\.|,)\d*)?$/;
function validateInput(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
// Valid input; update previousValue:
previousValue = newValue;
} else {
// Invalid input; reset field value:
event.target.value = previousValue;
}
}
document.getElementById('myInput').onkeyup = validateInput;
}());
Working demo: http://jsfiddle.net/8kUdG/
It's worth noting that this will also validate empty strings, as well as unfinished numbers, like 5, or 42. (otherwise the user would have to insert the decimal sign after typing the decimals, which would be... weird).
And finally, keep in mind that this might not be a cross-browser safe solution. If you need a pure-JavaScript solution, you will need to refine it (i.e., this might not work in IE).
Edit: of course, showing an error message instead of resetting the input field to the previous value is also perfectly possible (updated JSFiddle):
(function() {
var pattern = /^(?=.)\d*(?:[.,]\d+)?$/;
var error = document.getElementById('error');
document.getElementById('myInput').onkeyup = function(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
error.innerHTML = '';
} else {
error.innerHTML = 'Not a valid number!';
}
};
}());
I leave it up to you to replace the alert with something more user-friendly.
The easiest solution would be something like this
// Returns true on valid, false on invalid
function myInputFilter(input)
{
var value = input.value;
var regex = /^[\d\,\.]*$/;
if(!regex.test(value))
return false;
return true;
}
You could edit the function to just take a string argument, but I've chosen to have it accept the text input element instead. The RegEx can be replaced by anything, I've made a simple one for this example. I would refine it a bit if I were you (You can use the excellent online tool RegExr)
Here is an example of the filter implemented
http://jsfiddle.net/kVV77/
You can use following regular expression:
/^[+-]?(?=.)(?:\d+,)*\d*(?:\.\d+)?$/
to allow only any number of comma and only one dot . with the condition that number cannot start with a comma. Number can have optional + or - at the start.
I have a text field that allows a user to enter their age. I am trying to do some client-side validation on this field with JavaScript. I have server-side validation already in place. However, I cannot seem to verify that the user enters an actual integer. I am currently trying the following code:
function IsValidAge(value) {
if (value.length == 0) {
return false;
}
var intValue = parseInt(value);
if (intValue == Number.NaN) {
return false;
}
if (intValue <= 0)
{
return false;
}
return true;
}
The odd thing is, I have entered individual characters into the textbox like "b" and this method returns true. How do I ensure that the user is only entering an integer?
Thank you
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('I am an int');
...
}
That will absolutely, positively fail if the user enters anything other than an nonnegative integer.
For real int checking, use this:
function isInt(value) {
return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10));
}
The problem with many int checks is that they return 'false' for 1.0, which is a valid integer. This method checks to make sure that the value of float and int parsing are equal, so for #.00 it will return true.
UPDATE:
Two issues have been discussed in the comments I'll add to the answer for future readers:
First, when parsing string values that use a comma to indicate the decimal place, this method doesn't work. (Not surprising, how could it? Given "1,001" for example in the US it's an integer while in Germany it isn't.)
Second, the behavior of parseFloat and parseInt has changed in certain browsers since this answer was written and vary by browser. ParseInt is more aggressive and will discard letters appearing in a string. This is great for getting a number but not so good for validation.
My recommendation and practice to use a library like Globalize.js to parse numeric values for/from the UI rather than the browser implementation and to use the native calls only for known "programmatically" provided values, such as a string parsed from an XML document.
use isNaN(n)
i.e.
if(isNaN(intValue))
in place of
if (intValue == Number.NaN)
UPDATE
I have fixed the code that had an error and added a var called key to store the key pressed code using keyCode and which, that depend of the browser.
var key = e.which || e.keyCode;
Thanks Donald.McLean :)
If you want to check if you are writing numbers while typing (and avoid writing other characters into your input field), you can use this simple function and you can define the elements allowed (this include whatever you want to filter). In this way you can choose not only integers but for example a certain group of characters. The example is based in jQuery to attach it to an input field.
$('#myInputField').keypress(function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval of values (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
If you use other key than the defined, it won't appear into the field. And because Angular.js is getting strong these days. this is the directive you can create to do this in any field in your web app:
myApp.directive('integer', function()
{
return function (scope, element, attrs)
{
element.bind('keydown', function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
}
});
But what happens if you want to use ng-repeat and you need to apply this directive only in a certain number of fields. Well, you can transform the upper directive into one prepared to admit a true or false value in order to be able to decide which field will be affected by it.
myApp.directive('rsInteger', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (attrs.rsInteger === 'true') {
element.bind('keydown', function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
}
}
}
});
To use this new directive you just need to do it in a input type text like this, for example:
<input type="text" rs-integer="true">
Hope it helps you.
I did this to check for number and integer value
if(isNaN(field_value * 1) || (field_value % 1) != 0 ) not integer;
else integer;
Modular Divison
Example
1. 25.5 % 1 != 0 and ,
2. 25 % 1 == 0
And
if(field_value * 1) NaN if string eg: 25,34 or abcd etc ...
else integer or number
function isInt(x) {return Math.floor(x) === x;}
If your number is in the 32bit integer range, you could go with something like:
function isInt(x) { return ""+(x|0)==""+x; }
The bitwise or operator forces conversion to signed 32bit int.
The string conversion on both sides ensures that true/false want be matched.
Nobody tried this simple thing?
function isInt(value) {
return value == parseInt(value, 10);
}
What's wrong with that?
You may use isInteger() method of Number object
if ( (new Number(x)).isInteger() ) {
// handle integer
}
This method works properly if x is undefined or null. But it has poor browser support for now
I found the NaN responses lacking because they don't pick up on trailing characters (so "123abc" is considered a valid number) so I tried converting the string to an integer and back to a string, and ensuring it matched the original after conversion:
if ("" + parseInt(stringVal, 10) == stringVal) { alert("is valid number"); }
This worked for me, up until the numbers were so large they started appearing as scientific notation during the conversion.
...so of course this means you could enter a number in scientific notation, but checking minimum and maximum values as well would prevent that if you so desire.
It will of course fail if you use separators (like "1,000" or "1.000" depending on your locale) - digits only allowed here.
If (enteredAge < "1" || enteredAge > "130") ......
Simple and it works....until they develop immortality