how to link external js file in jsp

Went through other similar question on SO, but unable to fix my issue. I have written src path inside script tag.

Below is the program:

    function validate()
    {
        var fname = document.myForm.fname.value;
        var lname = document.myForm.lname.value;
        
        if(fname=="" && lname=="")
        {
            alert("First and last name cannot be emtpy");
            return false;
        }
    }
<html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <script src="/js/validation.js"></script>
            <title>Registration Form</title>
        </head>
        <body>
            <form name="myForm" action="RegistrationServlet.do" method="POST" onsubmit="return validate()">
            First name:<input type="text" name="fname" /> <br/>
            Last name:<input type="text" name="lname" /><br/>
            Gender: Male<input type="radio" name="male" /> Female<input type="radio" name="male" /><br/>
            Mobile:<input type="tel" name="mobile" /><br/>
            Email:<input type="email" name="email" /><br/>
            Address:<textarea name="tarea"></textarea><br/>
            Street:<input type="text" name="street" /><br/>
            Area:<input type="text" name="area" /><br/>
            
            City:<select>
                <option value="hyderabad">hyderabad</option>
                <option value="secunderabad">secunderabad</option>
                <option value="delhi">delhi</option>
                <option value="mumbai">mumbai</option>
            </select>
    
            State: <input type="text" name="state" /><br/>
            Country: <input type="text" name="country" /><br/>
            Pin: <input type="text" name="pin" /><br/>
            <input type="submit" value="Submit" />
            </form>
        </body>
    </html>

My js file is in the folder called js inside the webapp directory

Answers:

Answer

The correct link is:

<script src="/js/validation.js"></script>

Note correct spelling of src attribute.

You could also include the request context, although the leading / should be sufficient under most circumstances.

Unrelated, but you should probably trim leading/trailing white space in your validation routine, and you spelled empty wrong.

Answer

The below line fixed my problem:

<script src="<%request.getContextPath()%>/js/validation.js"></script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.