如何在输入或使用 jQuery 粘贴时禁止字符(并替换它们)? [英] How to disallow characters (and replace them) on type or paste with jQuery?

查看:18
本文介绍了如何在输入或使用 jQuery 粘贴时禁止字符(并替换它们)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种方法来替换不允许输入或粘贴到表单中所有输入字段(本质上是文本框和文本区域)的字符.每当用户粘贴包含一个或多个不允许的字符的文本时,我都希望将字符替换为空字符串",但其余文本保持不变.如果他们键入并键入字符,我只希望什么都没有"发生(例如,如果他们键入字符就不会出现).

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).

是否有关于如何执行此操作的代码示例或已经执行此操作的 jQuery 插件(以及如何实际使用它的示例)?我正在尝试查找适用于任何形式的粘贴(从浏览器菜单、鼠标/菜单命令、用于粘贴的操作系统快捷方式等)以及通过键入直接用户输入的方式.

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 }.

推荐答案

会是这样的:

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

演示:http://jsfiddle.net/RaphaelDDL/VB32P/

这篇关于如何在输入或使用 jQuery 粘贴时禁止字符(并替换它们)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆