Search code examples
javascriptjqueryhtmlkeyboard-eventskeyup

How to remap keyboard within the same textarea


Currently i am doing a project with remapping characters to words by detecting the keyup function. Unfortunately, i have only been able to retrieve the first character and remap to the word i want. In my project, i need to directly retrieve all of my keyboard input and directly convert it to the word that i want within the same textarea. For example when i type in the textarea, it will convert to "are" directly. I don't know why it stopped retrieving the second character and remapping not function. Below is my code, hope someone can tell me my error. Thank you.

<textarea class="width-100" id="translated-text"  onkeyup="myFunctionkey(event);" rows="10"></textarea>
<script>
function myFunctionkey(e) {
conversion();
}

function conversion(){
var x = document.getElementById('translated-text');
if(x.value == 'a'){
x.value='yes';
}
if(x.value == 'q'){
x.value = 'are';
}
}
</script>

Solution

  • From what I understand, you only want to grab the input and replace a key stroke with a complete word.

    Maybe this will do. I've changed onkeyup to onkeypress because this is more reliable from what I remember.

    <textarea id="translated-text" cols="50" rows="10" onkeypress="replaceInputChar(event);"></textarea>
    <script type="text/javascript">
        //create replacement map
        var map = {
            "a": "and",
            "b": "bold",
            "c": "change"
        };
    
    
        function replaceInputChar(e)
        {
            var ctl = document.getElementById("translated-text"); //control
            var char = String.fromCharCode(e.keyCode); //typed char
    
            if (char in map) //check if letter is defined in map
            {
                //insert replacement instead of letter
                if("selectionStart" in ctl)
                {
                    //in modern browsers we can easily mimic default behavior at cursor position
                    var pos = ctl.selectionStart;
                    ctl.value = ctl.value.substr(0, pos) + map[char] + ctl.value.substr(ctl.selectionEnd);
                    ctl.selectionStart = pos + map[char].length;
                    ctl.selectionEnd = ctl.selectionStart;
                }
                else
                    ctl.value += map[char];
    
                if ("preventDefault" in e) //modern browser event cancelling
                    e.preventDefault();
                else
                {
                    //old browser event cancelling
                    e.returnValue = false; //IE8
                    return false;
                }
            }
        }
        </script>