0

I am trying to validate my form using javascript. I want that if a user leaves an input field empty then he will see an alert and the form will not submit data to php file. Unfortunatlly, the code below is not working for me. javascript is not executing on form submit.

javascript

 <script>
 function MyForm() {
 var x =document.forms["myForm"]["name"].value;
  if (x == null || x == "")     {alert("Name must be filled out");
    return false;
   }
  { var y=document.forms["myForm"]["age"].value;
 if (y == null || y == "") {
    alert("age must be filled out");
    return false;
  }
 }

form

 <form name="myForm"action="game.php"onsubmit="return myForm()"method="post">



  Name: <input type="text" name="name">

 Age: <input type="text" name="age">
 <input type="submit" value="Submit">
 </form>

Any help is greatly appriciated.

3 Answers 3

2

You've got a couple typos in your code. A good way to find them is to use the console in the developer tools of your browser (try pressing F12).

Change

{ var y=document.forms["myForm"]["age"].value;

to

var y=document.forms["myForm"]["age"].value; //removed the opening curly brace

and in your form change:

onsubmit="return myForm()"

to

onsubmit="return MyForm()"
Sign up to request clarification or add additional context in comments.

Comments

1

you have to invoke myForm function first to make it work

  function MyForm() {
 var x =document.forms["myForm"]["name"].value;

  if (x == null || x == "")   
      {alert("Name must be filled out");
    return false;
   }
  var y=document.forms["myForm"]["age"].value;
 if (y == null || y == "") {
    alert("age must be filled out");
    return false;
  }
 }
 MyForm(); // invoke it here

1 Comment

the invocation is in the form's onsubmit. There's just a typo in there (first letter is lower case).
1

There are 2 typo issue in your javascript method. Try below method

function MyForm() {
   var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "")     {
         alert("Name must be filled out");
         return false;
    }
    var y=document.forms["myForm"]["age"].value;
    if (y == null || y == "") {
          alert("age must be filled out");
           return false;
     }
 }

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.