Reputation: 175
I'm trying to stop the following keypresses to happen before they happen:
' " / * - +
I've tried using various variations of the following:
<textarea>Here may the forbidden characters not enter</textarea>
<script>
function onKeyDown(event) {
event.preventDefault();
}
</script>
..but haven't succeded. The background is that it's linked to a jQuery which updates a database instantly, but I do not wish to see these characters in the database and need therefor stop them before they happen. Ideas?
Upvotes: 0
Views: 70
Reputation: 411
While it's not a good idea to have your client side code write to the database, quite a bad one actually, one solution is to event.preventDefault()
whenever someone types.
$(document).on("keydown", function(e){
var k = e.keyCode;
var nonShifted = [222, 191, 189];
var shifted = [56, 187];
if (nonShifted.indexOf(k) !== -1 || (shifted.indexOf(k) !== -1 && e.shiftKey)){
e.preventDefault();
}
})
Upvotes: 0
Reputation: 2341
Instead of preventing specific keypresses you could also clean up your textarea on change and keyup events like this:
$("#thisTextarea").change(function() { removeSpecialChars($(this)) });
$("#thisTextarea").keyup(function() { removeSpecialChars($(this)) });
function removeSpecialChars($textarea) {
$textarea.val($textarea.val().replace(/\'|\"|\/|\*|\-|\+/g,''));
}
https://jsfiddle.net/wagbw8nh/
Upvotes: 0