我有一段 HTML,它创建了一个包含三个文本字段(名称、组和编号)的 Web 表单,所有这些文本字段都使用 JavaScript 进行验证以检查是否有数据输入到其中。在最后一个文本字段中,我需要引入一点额外的 JavaScript 来检查用户输入的数据是否也是四位数字(例如 2947 或 94Q3)。作为一个完整的 JavaScript 新手,我不确定我会怎么做!我是否必须创建一个变量来获取输入数据的值,然后计算变量的位数,或者我可以直接从字段中进行计算吗?这是我的代码的 Javascript 部分:
function validateForm() {
var result = true;
var msg = ””;
if (document.Entry.name.value == ””) {
msg += ”You must enter your name\n”;
document.Entry.name.focus();
document.getElementById(‘name’).style.color = ”red”;
result = false;
if (document.Entry.group.value == ””) {
msg += ”You must enter the group\n”;
document.Entry.group.focus();
document.getElementById(‘group’).style.color = ”red”;
result = false;
}
if (document.Entry.number.value == ””) {
msg += ”You must enter the number\n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color = ”red”;
result = false;
}
if (msg == ””) {
return result;
} {
alert(msg)
return result;
}
}
如果可能,您能告诉我需要插入什么代码吗?谢谢!
最佳答案
将此 block 放在您的条件列表中:
if (document.Entry.number.length!=4) {
msg+=”You must enter 4 digits \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
关于javascript:计算文本输入中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26026404/