Ad

Stop Keypress Before It Happens

- 1 answer

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?

Ad

Answer

This code will prevent ", ', *, +, -, / characters in a <textarea>.

$(function(){
    // ", ', *, +, -, /
    var disabledOn = [34, 39, 42, 43, 45, 47];
    $('textarea').on('keypress', function(ev){
    if ($.inArray(ev.which, disabledOn) >= 0){
        ev.preventDefault();
    }
  });
})

Fiddle

Ad
source: stackoverflow.com
Ad