How to add character to textArea on keypress? - javascript

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);

Related

I want to include the negative sign for input by a function

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.

Detect Alt/Option + another key in textarea

I want to detect when the Alt/Option key and any other key are both pressed down simultaneously in a textarea on Mac. For example, I want to check for Alt/Option + 'h':
HTML
<textarea onkeydown="myFunction(event);"></textarea>
JavaScript
function myFunction(e) {
if (e.altKey && e.key=="h") {
// Do something here
}
}
The function works if I use Control instead of Alt. How can I get this to work with Alt on Mac?
JSFiddle
You can do this by directly ASCII value e.keyCode === 65 instead of checking by e.key == 'A'
function myFunction(e)
{
if ( e.altKey && e.keyCode === 65) //it check both altKey + 'A' or 'a'
{
//do something
}
}
i just did this for alt + a press. but you can do with any key by getting it's ASCII values
JsFiddle link for demo

Determine if key pressed is writing something - Javascript

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" />

Capturing ctrl+z key combination in javascript

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
}
});

Javascript onkeydown percent or five number

Is there any way to find out if the user pressed the percent key or 5 number? It has the same keycode in FireFox.
You can check for modifier keys provided by the event object. event.shiftKey is for your specific use case. In addition there are the event.altKey, event.ctrlKey and event.metaKey (for windows key in windows and command key in MAC keyboards) properties of the event.
In a code example you would have to perform the check inside your keyCode handler:
var NUMBER_FIVE = 53;
element.onkeydown = function (event) {
if (event.keyCode == NUMBER_FIVE) {
if (event.shiftKey) {
// '%' handler
} else {
// '5' handler
}
}
};
In addition when using event.keyCode you are handling what the user pressed on the keyboard. If you want to be checking for specific ASCII characters then you can use event.charCode instead because this event property tells you what character the user is inputting instead of telling you what the user is pressing on the keyboard. Here's a complete guide for this on quirksmode.
If you use keydown, 5 and % are the same keyCode. The event object also has a shiftKey boolean property that will tell you if the user is holding shift.
document.onkeydown = function (e) {
if (e.keyCode === 53) {
if (e.shiftKey) {
// they pressed %
} else {
// they pressed 5
}
}
};
If you want to use keypress, they are two different keyCodes:
document.onkeypress = function (e) {
if (e.keyCode === 53) {
// they pressed 5
}
if (e.keyCode === 37) {
// they pressed %
}
};
This site is good for testing keyCodes.
Checking shiftKey value: jsfiddle
$(document).keydown(function(e){
if( e.keyCode == 53 ){
if(e.shiftKey){
// % pressed
}
else{
// 5 pressed
}
}
});​
I test for both the keyCode and the value of the character being entered.
$(document).on({
keypress: function(event){
var charCode = (event.which) ? event.which : event.keyCode;
var mFive = String.fromCharCode(event.which);
if ((charCode == 53) && (mFive === "5")){
return true;
}else if ((charCode == 53) && (mFive !== "5")){
return false;
}
});

Categories

Resources