0

I want to replace a with b but i always see a before b. I tried it with other events like keyup, keydown, event.preventDefault but neither of them worked. How can i prevent this "a" view when user types ?

$("#text").keypress(function(event) {
  text2 = $(this).val();
  text2 = text2.replace(/(a)/g, "b");
  $("#text").val(text2);
});

//i tried with keyup, keydown also...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text"></textarea>

1
  • why -1 already ????? sorry but please don't send me a link saying "this question is already answered" because i checked it before posting Commented Aug 10, 2018 at 11:39

1 Answer 1

3

Using event.preventDefault:

$("#text").keypress(function(event) {
  if (event.key === "a") {
    event.preventDefault(); // <================
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text"></textarea>

That just prevents the a from appearing. If you want to insert b instead of a when the user types a, you'll need the techniques in this question's answers. Just calling .val(..) will mess up the user's cursor position (try typing in front of existing text when updating the value with val to see the problem).

Live example using Tim Down's answer to that question:

$("#text").keypress(function(event) {
  if (event.key === "a") {
    event.preventDefault();
    insertTextAtCursor(this, "b");
  }
});
function insertTextAtCursor(el, text) {
    var val = el.value, endIndex, range;
    if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
        endIndex = el.selectionEnd;
        el.value = val.slice(0, el.selectionStart) + text + val.slice(endIndex);
        el.selectionStart = el.selectionEnd = endIndex + text.length;
    } else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
        el.focus();
        range = document.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text"></textarea>

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

6 Comments

okay sir this is not exactly what i wanted because i tried it before but thank you
@pinug - How so?
oh i didn't see your last post yes that's it sir !
Well, all I did with the update was show an example of applying the techniques I'd already pointed to.
sir how can do this with "abc" -> "b" for instance. because event.key gets only one letter am i wrong ? :/ @T.J. Crowder
|

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.