【发布时间】:2015-01-13 21:21:37
【问题描述】:
在使用 JavaScript 函数时,如果字符不符合某些参数,我想防止它们被输入到表单中。我使用的原始 JavaScript 代码是:
function validateLetter() {
var textInput = document.getElementById("letter").value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
document.getElementById("letter").value = replacedInput;
}
当我在表单中仅使用 1 个输入点时,该函数有效,但是当我尝试在多个输入上使用该函数时,它只会影响表单中的第一个输入点。
当创建一个可以被多个输入框重复使用的函数时,我得到了以下代码:
function validateLetter(dataEntry){
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
}
catch(InputError) {
window.alert(InputError)
return false;
}
return true;
}
我用来输入信息的表格是:
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded">
<p>Enter your mother's maiden name:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the city you were born in:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter" name="letter" onkeypress="validateLetter()">
</p>
</form>
有谁知道翻译第一个函数最后一行的方法:document.getElementById("letter").value = replaceInput;
可以在当前代码中重复使用的东西。
我试过了: dataEntry.value = 替换输入 但这似乎根本没有运行/更改功能
【问题讨论】:
-
既然你标记了
HTML5,你考虑过<input pattern="[^A-Za-z]">吗? -
您的文本输入都具有相同的id,并且您使用id获取元素,只有第一个元素通过“document.getElementById("letter")”获取,这就是为什么只有第一个文本输入可以工作。
-
我研究过使用 但这只会阻止数据在不符合参数时被提交,我想防止无效字符根本不会被输入到盒子里
标签: javascript html