How to disallow characters (and replace them) on type or paste with jQuery?

℡╲_俬逩灬. 提交于 2021-02-05 07:12:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!