我试图避免在page.php上输入除数字和字母外的任何标记
<input type="text" id="input"> 从这个答案来看,only allow English characters and numbers for text input <input type="text" id="input" class="clsAlphaNoOnly">:
$(document).ready(function () {
$('.clsAlphaNoOnly').keypress(function (e) { // Accept only alpha numerics, no special characters
var regex = new RegExp("^[a-zA-Z0-9 ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
})或者这个:
$(function(){
$("#input").keypress(function(event){
var ew = event.which;
if(ew == 32)
return true;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
return false;
});
});在这两种情况下,字符串都是明确的,但我使用两种类型的输入,单击$("#btn").click(function()按钮来处理输入,使用$(document).keypress(function(e)在键盘上按回车键输入相同的输入。由于某种原因,如果我包括此方法以避免字符串中的额外标记,按enter键不允许输入插入的值。
这种方法工作得很好:
<input type="text" id="input" onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />但是,我希望避免在html中使用page.php中的额外代码。我想弄清楚,是什么原因阻止用给定的方法输入插入的值
发布于 2019-08-28 18:28:29
会告诉你可能错过了事件参数吗?
在没有jQuery的情况下,我可以在3种浏览器中这样工作:
function clsAlphaNoOnly (e) { // Accept only alpha numerics, no special characters
var regex = new RegExp("^[a-zA-Z0-9 ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
}
function clsAlphaNoOnly2 () { // Accept only alpha numerics, no special characters
return clsAlphaNoOnly (this.event); // window.event
}<input type="text" id="input" onkeypress="clsAlphaNoOnly(event)" onpaste="return false;">
<input type="text" id="input" onkeypress="clsAlphaNoOnly2()" onpaste="return false;">
发布于 2019-08-28 18:20:49
发布于 2019-08-28 22:01:30
如果您真的不想使用Regex方法作为以下建议的注释,那么您可以使用以下简单代码:
document.querySelector("input#testInput").addEventListener("input", function(){
const allowedCharacters="0123456789azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBNzáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ "; // You can add any other character in the same way
this.value = this.value.split('').filter(char => allowedCharacters.includes(char)).join('')
});<input type="text" id="testInput">
https://stackoverflow.com/questions/57698005
复制相似问题