pinug
pinug

Reputation: 211

Prevent keypress default value when user types

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>

Upvotes: 0

Views: 287

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

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>

Upvotes: 3

Related Questions