0

i have currently got a javascript code which validates my form and shows an error if a field is not completed. i also want to know how i could echo out the errors in the form so for instance if 'fname' is not filled in then this says 'You did not fill in fname' or if 'fname' and fcompany' are not filled in this says

You did not fill in fname 
you did not fill in fcompany 

Heres my html:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Company Name: <input type="text" name="fname">
Company Registration Number: <input type="text" name="fcompany">

heres my javascript:

<script>
function validateForm()
 {
 var x=document.forms["myForm"]["cname"].value;
 if (x==null || x=="")
   {
document.body.scrollTop = document.documentElement.scrollTop = 0;
   document.getElementById("alertBox").style.display='block';
   return false;
   }
 }
</script>
1
  • document.getElementById("alertBox").innerHTML = "Your error here" ? Commented Mar 31, 2014 at 11:31

1 Answer 1

1

Have your validate function build an array of errors, then have another function take the errors array and build the HTML:

http://jsfiddle.net/J9LJj/

function displayErrors(errors){
    var container = document.getElementById("alertBox");
    var html = "<ul>";

    for(var i=0; i<errors.length; i++){
        html += "<li>" + errors[i] + "</li>";
    }
    html += "</ul>";

    container.innerHTML = html;
    container.style.display = "block";
}

function validateForm(){
    var fname = document.forms["myForm"]["fname"].value;
    var fcompany= document.forms["myForm"]["fcompany"].value;

    var errors = [];

    if(fname == ""){
        errors.push("you did not fill in fname");
    }
    if(fcompany == ""){
        errors.push("you did not fill in fcompany");
    }

    if(errors.length > 0){
        displayErrors(errors);
        return false;
    } else {
        return true;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

hi thanks for this but its not working, its not cancelling the default action of the form and the form is submitting to the next page, without showing any errors. i want to disbale the default form action and display the errors on the parent page
This is working, see this demo: jsfiddle.net/J9LJj if it's not working for you, check the field names fname and cname are correct for your actual form. Also look at the error console (F12) which should narrow the problem down.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.