0

Let's say there is textarea with already present text for example: AA. How we can detect the pressed key and change only this character with something else. Now if A key is pressed through keyboard text should become AAB already existing A characters are unaltered but newly pressed A key should write B in textarea.

The code I have is

<textarea>aa</textarea>

<script>
    jQuery('textarea').keyup(function (e) {
        //THIS REPLACES ALL THE TEXT NOT JUST THE PRESSED CHARACTER
        //Need code that should replace just this pressed key not all text of textarea
        jQuery('textarea').val(jQuery('textarea').val().replace(/a/g, "b"));
    });
</script>

Ideal solution will select character from pressed key e and replace it, but if not possible then maybe replacing last character in textarea can be a poor workaround.

Also ok if keypress, keydown or similar event is used.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
XIMRX
  • 2,130
  • 3
  • 29
  • 60
  • have you checked `e.keyCode`? – Daniel Cheung Jan 10 '16 at 07:42
  • Side note: please consider how your requirement interacts with selection - typing single character can replace selection (whole text/part) - make sure you understand what you want to do in such case. – Alexei Levenkov Jan 10 '16 at 07:47
  • Seems too broad to me. – Jai Jan 10 '16 at 07:48
  • when do you want to replace the text in textarea ? starting from which character ? – Arkantos Jan 10 '16 at 07:52
  • @DanielCheung yes e.keyCode gives what key is pressed but `if (e.keyCode==65) e.keyCode = 66;` don't work. How can I replace The pressed key even after knowing its code – XIMRX Jan 10 '16 at 07:52
  • What is expected result when third character within `textarea` ? – guest271314 Jan 10 '16 at 07:52
  • @AlexeiLevenkov my code is wrong that is why i mentioned comment, what replace is doing there is Wrong. What is needed is explained in question – XIMRX Jan 10 '16 at 07:54
  • @Arkantos don't need 'string replacement' I need the pressed key character replaced with something else – XIMRX Jan 10 '16 at 07:54
  • You need to add some more context here. When you say `key should be replaced`, you need to be specific. Should you replace when you enter a specific key, if so what are the allowed keys and their replacements. – Arkantos Jan 10 '16 at 07:56
  • @Arkantos Whenever A is pressed B should be written in textarea without replacing already present A characters of textarea – XIMRX Jan 10 '16 at 08:00
  • Does that mean that you're `textarea` will always have some default text and if the user starts to edit it your replace should kick-in ? – Arkantos Jan 10 '16 at 08:04
  • @Arkantos Yes. I think I can make what I need out of DanielCheung's answer – XIMRX Jan 10 '16 at 08:11

1 Answers1

3

Try this:

Since e.keyCode is read-only. I stopped it from entering and added altered characters.

Credits to MarkPiezak, part of code from here: Set keyboard caret position in html textbox

$(function(){
  $("#ta").keydown(function(e){
    var newKey = e.keyCode + 1;
    var newChar = String.fromCharCode(newKey);
    $("#pressed-key").text(e.keyCode + "->" + newKey + "->" + newChar);
    if (e.keyCode > 47 && e.keyCode < 91) {
      e.preventDefault();
      var cursorPosition = $('textarea').prop("selectionStart");
      var ta = document.getElementById("ta");
      ta.value = [ta.value.slice(0, cursorPosition), newChar, ta.value.slice(cursorPosition)].join('');
      setCaretPosition("ta", cursorPosition+1);
    }
  });
  
  //This one is from https://stackoverflow.com/questions/512528/set-cursor-position-in-html-textbox
  function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
  }
  
  
  $("#ta2").keydown(function(e){
    var sentence = "I am a monster!";
    if (e.keyCode > 47 && e.keyCode < 91) {
      e.preventDefault();
      var ta = document.getElementById("ta2");
      ta.value += sentence[ta.value.length] || "";
    }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="ta">aa</textarea>
<p id="pressed-key"></p>

<hr>
<p>This one is just for fun. Try answering this: Who are you?</p>
<textarea id="ta2"></textarea>
Community
  • 1
  • 1
Daniel Cheung
  • 4,779
  • 1
  • 30
  • 63