当我按下提交按钮时,我需要检查“名字”和“父亲姓名”文本字段的长度,如果超过20个字符,我需要在文本字段前面以红色显示错误消息。我的代码工作正常,只是它显示错误消息,每一件事都在一秒钟内消失。我需要错误消息留在那里。这是我的java脚本函数:
<head>
<script type="text/javascript">
function validate()
{
var firstName=document.f1.firname.value;
var fatherName=document.f1.fname.value;
var address=document.f1.add.value;
var phoneNumber=document.f1.ph.value;
var cnic=document.f1.cnic.value;
var email=document.f1.email.value;
var cgpa=document.f1.fname.value;
var sem=document.f1.sem.value;
var id=document.f1.cid.value;
if(firstName.length>20)
{
document.getElementById("fin").innerHTML="can't exceed 20 characters!";
}
if(fatherName.length>20)
{
document.getElementById("fn").innerHTML="can't exceed 20 characters!";
}
}
</script>
</head>
相应的文本字段为:
<form name="f1" onsubmit="validate()">
Name : <input type="text" name="firname"> <span id="fin" style="color:red"></span> <br>
Father's Name: <input type="text" name="fname"> <span id="fn" style="color:red"></span><br>
</form>
答案 0 :(得分:1)
试试这个:(@ NeilThompson在评论中提到):
<form name="f1" onsubmit="return validate();"> //put return
并在你的javascript代码中输入:
<head>
<script type="text/javascript">
function validate()
{
var flag = true;
var firstName=document.f1.firname.value;
var fatherName=document.f1.fname.value;
var address=document.f1.add.value;
var phoneNumber=document.f1.ph.value;
var cnic=document.f1.cnic.value;
var email=document.f1.email.value;
var cgpa=document.f1.fname.value;
var sem=document.f1.sem.value;
var id=document.f1.cid.value;
if(firstName.length>20)
{
document.getElementById("fin").innerHTML="can't exceed 20 characters!";
flag = false;
}
if(fatherName.length>20)
{
document.getElementById("fn").innerHTML="can't exceed 20 characters!";
flag = false;
}
return flag;
}
</script>
</head>