I want to run an action only if the key pressed is writing something, so it ignores arrow keys, shift key or enter key etc.
I am using the following script, but I would like to find an alternative to Improve it.
$('body').on('keyup', 'input', function(e) {
if (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode >= 65 && e.keyCode <= 90 || e.keyCode >= 97 && e.keyCode <= 122) {
// do something
}
});
From the comments:
the problem is my script include only the Number, Alphabet upper case and Alphabet lower case.I want to run action only if input content change
In order to trigger an event when text changes in the input, you need to define a global variable holding the previous data of the input.
Then when a keyup event is fired, you can check whether the input_data==new_input_data, then do whatever you want.
var input_data, new_input_data;
input_data = $("#myinput").val();
new_input_data="";
$('body').on('keyup', 'input', function(e) {
new_input_data = $("#myinput").val();
if(input_data!=new_input_data){
alert("text changed");
input_data = new_input_data;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myinput" />
Related
hi i have this function to allow digits 0-9 but i want to include the negative sign. how would i do that? Thanks.
function allowNumbersOnly(e) {
var code = (e.which) ? e.which : e.keyCode;
if (code > 31 &&(code < 48 || code > 57)) {
e.preventDefault();}
else if (code==109){
e.preventDefault();
}
}
Also see HTML text input allow only numeric input.
Add a test to check if it's the first character and allow "-". Otherwise, run the other tests. e.g.
function allowNumbersOnly(e) {
let len = e.target.value.length;
var code = (e.which) ? e.which : e.keyCode;
if (len == 0 && code == 45) {
return;
}
if (code > 31 && (code < 48 || code > 57)) {
e.preventDefault();
} else if (code == 109) {
e.preventDefault();
}
}
window.onload = function() {
document.querySelector('#i0').addEventListener('keypress', allowNumbersOnly, false);
}
<input id="i0">
However, that only allows entry of "-" as the first and only character, it can't be added later to change say "1" to "-1".
Personally, I find this kind of UI feature very annoying, e.g. it prevents keystrokes to copy and paste values. Just let the user enter whatever they like and deal with it. If it doesn't fit the required criteria, just let the user know with a friendly message and let them fix it.
I'm trying to make a simple script. When a user presses a certain key, a character will be added to the value of a textarea. For example (this isn't my case), say the user presses the Alt + Enter keys. When they do so, I'd like to add a character onto the already existing text in the text field.
So, my code would be:
function doc_keyUp(e) {
if (e.altKey && e.keyCode == 13) {
*insert character into textarea*
}
}
document.addEventListener('keyup', doc_keyUp, false);
The code itself works fine- however, I'm unsure about how to insert the character. Any help is appreciated!
Just for reference, I'm attempting to create a simple phonetic keyboard for Ukrainian. You can type an English letter, and the Ukrainian counterpart shows up. Look at http://ua.translit.cc to better understand what I'm saying.
function doc_keyUp(e) {
if (e.altKey && e.keyCode == 13 || e.keyCode == 65) {
document.getElementById("area").value += "123";
}
}
function validateKey(e){
// here can be whatever keys
if (e.keyCode >= 65 && e.keyCode <= 90 || e.keyCode >= 97 && e.keyCode <= 122) return false;
}
document.addEventListener('keyup', doc_keyUp, false);
<textarea id="area" onKeyPress="return validateKey(event)">ABC</textarea>
Updated to validate some key in the entry of textarea.
You can just add the text to the value of the textarea.
function doc_keyUp(e) {
if (e.altKey && e.keyCode == 13) {
textarea.text += value
}
}
document.addEventListener('keyup', doc_keyUp, false);
I have a textfield in Extjs. This textfield can only contain
Digits 0 - 9
Alphabets a-z or A-Z
Characters like _ (underscore) and - (hyphen)
I want to prevent the user from entering anything apart from these characters. As such I wish to display an error, something like a red underline along with helptext to notify the user as to why the error is there.
Kindly advice as to how to go about preventing the user from entering anything apart from the above characters and also displaying the error message.
Use maskRe property:
An input mask regular expression that will be used to filter
keystrokes (character being typed) that do not match. Note: It does
not filter characters already in the input.
maskRe: /[A-Za-z0-9\-_]/
Working example: https://fiddle.sencha.com/#fiddle/o4b
Something like this. There are a whole load of issues with keypress and keydown on different browsers, but I believe this should work on most/all modern browsers without issue.
var errorDiv = document.getElementById('error'),
testInp = document.getElementById('test');
testInp.addEventListener('keypress', function (evt) {
var code = evt.keyCode || evt.charCode;
if (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 45 || code === 95) {
errorDiv.classList.add('hidden');
} else {
evt.preventDefault();
errorDiv.classList.remove('hidden');
}
}, false);
testInp.addEventListener('keydown', function (evt) {
var code = evt.keyCode || evt.charCode;
if (code === 8 || code >= 37 && code <= 40|| code === 46) {
errorDiv.classList.add('hidden');
}
}, false);
#error {
color: red;
}
.hidden {
visibility: hidden;
}
<input id="test" type="text" />
<div id="error" class="hidden">As such I wish to display an error, something like a red underline along with helptext to notify the user as to why the error is there.</div>
You can add an event keyup and check the input key value.
For example for a space:
listeners: {
keyup: function(field, e) {
var key = e.getKey();
if (key == 32){
alert("Hey dude, what are you doing?");
}
}
}
Or something else. You can take a look at:
field.addClass("x-form-invalid")
field.markInvalid("Hey dude, what are you doing?");
Hope this helps.
This is my input:
<input type='text' class='myprofiletags' name='my_profile_tags' value='' />
I want to alert and forbid the user if he/she writes the same word twice. I am entering values with commma e.g
games, animes, movies
jQuery('.myprofiletags').keypress(function(e)
{
if (jQuery(this).val().match(/,/g).length >= 10)
{
if(e.keyCode == 8 || e.keyCode == 46 || e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40)
{
}
else
{
e.preventDefault(); // stops the keypress occuring
alert('No more profile tags are allowed');
}
}
});
Set an event handler (onkeyup) on input box so that whenever user hits a key the handler gets called
In event handler take the values of input box and split them on comma
Check if any value is duplicate
If no return true
If yes show an alert
Synopsis:
$(".myprofiletags").keydown (function (e) {
alert ($(this).val());
});
You can also use change
$('input[name^="text"]').change(function() {
Edit: You are going in right direction, just split the value on comma and use each splitted value as an item of array.
See how to do that:
Split comma-separated input box values into array in jquery, and loop through it
Convert comma separated string to array
I am trying to capture ctrl+z key combination in javascript with this code:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<script type='text/javascript'>
function KeyPress(e) {
var evtobj = window.event? event : e
//test1 if (evtobj.ctrlKey) alert("Ctrl");
//test2 if (evtobj.keyCode == 122) alert("z");
//test 1 & 2
if (evtobj.keyCode == 122 && evtobj.ctrlKey) alert("Ctrl+z");
}
document.onkeypress = KeyPress;
</script>
</body>
</html>
Commented line "test1" generates the alert if I hold down the ctrl key and press any other key.
Commented line "test2" generates the alert if I press the z key.
Put them together as per the line after "test 1 & 2", and holding down the ctrl key then pressing the z key does not generate the alert as expected.
What is wrong with the code?
Use onkeydown (or onkeyup), not onkeypress
Use keyCode 90, not 122
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 90 && evtobj.ctrlKey) alert("Ctrl+z");
}
document.onkeydown = KeyPress;
Online demo: http://jsfiddle.net/29sVC/
To clarify, keycodes are not the same as character codes.
Character codes are for text (they differ depending on the encoding, but in a lot of cases 0-127 remain ASCII codes). Key codes map to keys on a keyboard. For example, in unicode character 0x22909 means 好. There aren't many keyboards (if any) who actually have a key for this.
The OS takes care of transforming keystrokes to character codes using the input methods that the user configured. The results are sent to the keypress event. (Whereas keydown and keyup respond to the user pressing buttons, not typing text.)
For future folks who stumble upon this question, here’s a better method to get the job done:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key === 'z') {
alert('Undo!');
}
});
Using event.key greatly simplifies the code, removing hardcoded constants. It has support for IE 9+.
Additionally, using document.addEventListener means you won’t clobber other listeners to the same event.
Finally, there is no reason to use window.event. It’s actively discouraged and can result in fragile code.
Ctrl+t is also possible...just use the keycode as 84 like
if (evtobj.ctrlKey && evtobj.keyCode == 84)
alert("Ctrl+t");
$(document).keydown(function(e){
if( e.which === 89 && e.ctrlKey ){
alert('control + y');
}
else if( e.which === 90 && e.ctrlKey ){
alert('control + z');
}
});
Demo
document.onkeydown = function (e) {
var special = e.ctrlKey || e.shiftKey;
var key = e.charCode || e.keyCode;
console.log(key.length);
if (special && key == 38 || special && key == 40 ) {
// enter key do nothing
e.preventDefault();
}
}
here is a way to block two keys, either shift+ or Ctrl+ key combinations.
&& helps with the key combinations, without the combinations, it blocks all ctrl or shift keys.
90 is the Z key and this will do the necessary capture...
function KeyPress(e){
// Ensure event is not null
e = e || window.event;
if ((e.which == 90 || e.keyCode == 90) && e.ctrlKey) {
// Ctrl + Z
// Do Something
}
}
Depending on your requirements you may wish to add a e.preventDefault(); within your if statement to exclusively perform your custom functionality.
The KeyboardEvent.keyCode is deprecated (link) think about using KeyboardEvent.key instead (link).
So, the solution would be something like this.
if (e.key === "z" && e.ctrlKey) {
alert('ctrl+z');
}
You can actually see it all in the KeyboardEvent when you use keydown event
Use this code for CTRL+Z. keycode for Z in keydown is 90 and the CTRL+Z is ctrlKey. check this keycode in your console area
$(document).on("keydown", function(e) {
console.log(e.keyCode, e.ctrlKey);
/*ctrl+z*/
if (e.keyCode === 90 && e.ctrlKey) { // this is confirmed with MacBook pro Monterey on 1, Aug 2022
{
//your code here
}
});