[英]How to remove special characters from input fields while pasting?
我正在嘗試實現功能,如果用戶粘貼文本,它應該刪除<
、 >
、 $
和!
.
以下代碼適用於所有輸入。 目前它禁用粘貼 function。
function specialCharRestriction() {
setTimeout(function(e) {
$('input, textarea').bind("cut copy paste", function(e) {
e.preventDefault();
});
$('input:not([type=password]), textarea').on('keypress', function(e) {
var blockSpecialRegex = /[!$(){}[\]:;<+?\\>]/;
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (blockSpecialRegex.test(key)) {
e.preventDefault();
return false;
}
});
}, 500);
}
相反,我想要這樣的東西:
$('input').val().replace(regex, '');
這樣它就可以應用於所有輸入,我不必 select 一個一個地輸入所有輸入。 我的項目中聲明了 100 多個字段,因此請幫助提供一些可應用於所有輸入字段的通用代碼。
編輯:我希望每當有人粘貼<Naruto>
時,應該只粘貼Naruto
而 <> 應該被省略。 以下代碼只工作一次,然后粘貼特殊字符。
$('input, textarea').bind("input", function(e) { var blockSpecialRegex = /[:$(){}[\];?<+;\\>]/g. let txtOrig = $(this);val(). let txtFinal = txtOrig,replace(blockSpecialRegex; ''): if (txtOrig.== txtFinal) { // Some blocked special chars was found and removed // Warning; this will move the cursor to the end! $(this).val(txtFinal); } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> input1:<input id="txt1"><br> input2:<input id="txt2"><br> input3:<input id="txt3"><br> textarea1:<textarea id="txt4"></textarea><br> textarea2:<textarea id="txt5"></textarea><br> textarea3:<textarea id="txt6"></textarea><br>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.