Mo Mononoke
Mo Mononoke

Reputation: 175

Stop keypress before it happens

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

Answers (3)

Josh Alexy
Josh Alexy

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();
  }
})

codepen

Upvotes: 0

caulitomaz
caulitomaz

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

choz
choz

Reputation: 17858

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

Upvotes: 1

Related Questions