Question

I have a javascript function to validate a form.

<script type="text/javascript">
function formValidate()
        {
            // create array containing textbox elements
            var inputs = [document.getElementById('fname'), document.getElementById('lname'), document.getElementById('email1'), document.getElementById('email2'), document.getElementById('message')];

            var error;

            for(var i = 0; i<inputs.length; i++)
            // loop through each element to see if value is empty
            {
                if(inputs[i].value == '')
                {
                    error = 'Please complete all fields.';
                    alert(error);
                    return false;
                    }
            }
         }
</script>

It works when in the head of the html page, but not when I reference it from another file.

<script src="form.js" type="text/javascript"></script>

form code:

<form onsubmit="return formValidate()"  action="mailto:admin@sfasc.com.au" method="post"  id="contactForm" >

Can you please tell me what I'm doing wrong?

Was it helpful?

Solution

The content returned for the <script> tag should be only your JavaScript, and not include any HTML. That means your JS file should only include JS code and not the <script type="text/javascript"> and </script> parts. Your HTML file takes care of HTML, which is why you have <script src="form.js" type="text/javascript"></script>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top