I am working on java script and i am stuck on one phase. In my project i have to validate all fields when the form is submitted and display error message on same page in order list above the form field. bellow is my code
function validation(){
var errorMsg=new Array();
//var errorMsg = "";
if(document.getElementById("fullname").value = " "){
errorMsg[0] = "Please Enter Full Name\n"
}
if(document.getElementById("street").value = " "){
errorMsg[1]= "Please Enter Street Name\n"
}
if(document.getElementById("postcode").value = " "){
errorMsg[2]= "Please Enter Postlecode\n"
}
if(document.getElementById("phone").value = " "){
errorMsg[3]= "Please Enter Phone Number\n"
}
if(document.getElementById("email").value = " "){
errorMsg[4]= "Please Enter Email Id\n"
}
if(errorMsg!=" "){
var r =" ";
for(var i=0;i<=errorMsg.length-1;i++){
document.getElementById("error").innerHTML="<li>"+errorMsg[i]+"</li>"
}
return false;
}
}
</script>
when i run this code it gives me only last value
can anybody help me how to display error message on the top of the form?
You’ve got a mistake here:
You need to append
errorMsg, not to assign it. For example like this:If you want to display the error message on the top of the page, you should create div, where you want, give to this div the id and set innerHtml to this div:
Also you could improve your validation and validate fields when a user is typing, not after he submitted all information.
And by the way, you add errors in tag
<li>. So, you know that you should also add<ol>or<ul>to make a list?