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>