Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: form is not defined

Can't for the life of me figure this out. any help would be greatly appreciated!

This is the message I receive in Google Chrome when I test the script:

Navigated to http://localhost/contact.php form2.js:2 Uncaught ReferenceError: form is not definedform2.js:2 validatecontact.php:24 onsubmit Navigated to http://localhost/contact.php

My contact.php file:

<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="form2.js"></script>



<?php require 'Includes/Header.php'; ?>

    <div class="wrapper">
        <div id="contact-form">
        <h5>Contact Form</h5>
    <form name="contact" form method="post" action="contact.php" 
    onsubmit="return validate(contact)">

        <label for="name">Name:</label>
        <input type="text" id="name" name="name">

        <label for="email">Email:</label>
        <input type="email" id="email" name="email">

        <label for="message">Message:</label>
        <textarea id="message" name="message"></textarea>


        <button type="submit">Submit</button>
        </form>         
            <div class="clear"></div>
    </div>
    </div>


   <?php require 'Includes/Footer.php'; ?>

My form2.js file:

    function validate(contact){
    var name = form.name.value;
    var email = form.email.value;
    var message = form.message.value;

    if (name.length == 0 || name.length > 200)
    {alert ("You must enter a name.");
    return false;
    }

    if (email.length == 0 || email.length > 200)
    {alert ("You must enter a email.");
    return false;
    }

    if (message.length == 0)
    {alert ("You must enter a message.");
    return false;
    }

    return true;
}
like image 354
FaithR Avatar asked Sep 22 '26 10:09

FaithR


1 Answers

form is a javascript object. That object does not exist within this file, which is why the error is being thrown. If you want to validate this form, you need to get a reference to it from the DOM first, using document.contact.

function validate(contact){
  var form = document.contact,
      name = form.name.value,
      email = form.email.value,
      message = form.message.value;

  if (name.length == 0 || name.length > 200) {
    alert ("You must enter a name.");
    return false;
  }

  if (email.length == 0 || email.length > 200) {
    alert ("You must enter a email.");
    return false;
  }

  if (message.length == 0) {
    alert ("You must enter a message.");
    return false;
  }

  return true;
}
like image 87
Kevin Smith Avatar answered Sep 23 '26 23:09

Kevin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!