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.

12
  • have you checked e.keyCode? Commented Jan 10, 2016 at 7: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. Commented Jan 10, 2016 at 7:47
  • Seems too broad to me. Commented Jan 10, 2016 at 7:48
  • when do you want to replace the text in textarea ? starting from which character ? Commented Jan 10, 2016 at 7: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 Commented Jan 10, 2016 at 7:52

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks Daniel, I think I can get what I need out of this code, 'll edit ur answer a little and accept.
@XIMRX you should tell me what I need to edit. Because this is my answer :)
Ok :) the problem is when clicked at start or middle to add characters there, it adds them at end not where required.
This can be done using var cursorPosition = $('textarea').prop("selectionStart");
@XIMRX Well, I've not thought of that one :D not thorough enough on testing. Haha
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.