user7039315
user7039315

Reputation:

How to add character to textArea on keypress?

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.

Upvotes: 2

Views: 3511

Answers (2)

BrTkCa
BrTkCa

Reputation: 4783

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.

Upvotes: 2

Rohan Rao
Rohan Rao

Reputation: 112

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

Upvotes: 1

Related Questions