问题
I’m trying to find a way to replace disallowed characters from being entered or pasted into all input fields (textboxes and textareas essentially) in a form. Any time a user pastes text that contains one or more disallowed characters I would want the character replaced with an empty string ‘’ but have the rest of the text intact. If they type and type the character I would just want “nothing” to happen (e.g. the character not to appear if they type it).
Is there a code sample that exists on how to do this or a jQuery plug-in that already does this (with an example of how to actually use it)? I’m trying to find a way that works for any form of paste (from a browser menu, with mouse / menu commands, OS shortcut for paste, etc.) as well as direct user input through typing.
Specifically we need to disallow braces in the form of {
, [
, ]
, or }
.
回答1:
Would be something like this:
HTML
<textarea name="" id="text" cols="30" rows="10"></textarea>
JS
$(function(){
$('#text').on('keyup paste',function(){
oldtxt = $(this).val();
find = '(\{?)(\}?)(\\[?)(\\]?)';
newtxt = oldtxt.replace(new RegExp(find, 'g'), '');
$(this).val(newtxt);
});
});
Demo: http://jsfiddle.net/RaphaelDDL/VB32P/
来源:https://stackoverflow.com/questions/18153391/how-to-disallow-characters-and-replace-them-on-type-or-paste-with-jquery