0

I'm using JS for the first time. Can't seem to call an external JS function at all. I have a HTML form and im trying to call a function so if the first name box is empty, I get a message saying to fill in a name.

My form

<head>
<script type="text/javascript" src="scripts/validation.js"></script>
</head>

<body>
 <form name="myForm" method="post" action="somewhere.html" 
   onsubmit="validation()">

<fieldset id="PersonalDetails">
    <legend>Personal Details</legend>
    <div class="form" id="firstname">
    <p>First Name: <br />
    <input type="text" name="firstname" />
    </p>
    </div>
 </fieldset>
  </form>
 </body>

In the JS file:

 function validation(){
 var x=document.forms["myForm"]["firstname"].value;
 if (x==null || x=="")
 {
 alert("First name must be filled out!!!!");
 return false;
 }
}
3
  • 2
    Open up your developer console (usually F12 does it, but it varies) - do you see any errors? If you're a new dev, I can't stress the importance of the console enough, it's your best friend. Commented May 6, 2014 at 19:03
  • I don't see anything, but I don't know what im looking for. I'm just wondering how to call the funtion correctly. I know how to do it if the JS is in the HTML file, but not for an external js file Commented May 6, 2014 at 19:08
  • You're function call works, see jsfiddle - jsfiddle.net/ej7tY Commented May 6, 2014 at 19:23

3 Answers 3

2

you need to have a submit button in your form trigger the onsubmit event. Your function will be called if you've imported your javascript correctly. See below you're form with a submit button.

<body>
 <form name="myForm" method="post" action="somewhere.html" 
   onsubmit="validation()">

<fieldset id="PersonalDetails">
    <legend>Personal Details</legend>
    <div class="form" id="firstname">
    <p>First Name: <br />
    <input type="text" name="firstname" />
    </p>
        <input type='submit' value='submit'/>
    </div>
 </fieldset>
  </form>
 </body>
Sign up to request clarification or add additional context in comments.

Comments

1

Just change onsubmit="validation()" to onsubmit="return validation()"

Comments

0

Try this

change your form

<form name="myForm" method="post" action="#" onsubmit="validation()">

change your javascript

function validation(){
 var x=document.forms["myForm"]["firstname"].value;
 if (x==null || x==""){
     alert("First name must be filled out!!!!");
     return false;
 }else{
    document.forms["myForm"].setAttribute("action", "somewhere.html").submit();
 }
}

Comments

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.