XIMRX
XIMRX

Reputation: 2172

How to replace the pressed character only; Using Javascript/jQuery

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.

Upvotes: 0

Views: 1868

Answers (1)

Daniel Cheung
Daniel Cheung

Reputation: 4819

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>

Upvotes: 3

Related Questions