Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'reset' of null in Javascript

I am trying to validate email in a form input by a button click. Here is the code:

function ValidateEmail(inputText) {
  var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  if (inputText.value.match(mailformat)) {
    document.form1.coemail.focus();
    return true;
  } else {
    alert('You have entered an invalid email address!Enter again');
    document.getElementById('form1').reset();
    return false;
  }
}

<button class="btn btn-primary nextBtn btn-lg pull-right" type="button"onClick="ValidateEmail(document.form1.coemail)">Next</button>

On clicking the Next button I get an alert message correctly but after that it redirects to next page instead of resetting the current one. On inspecting element in chrome's console,I found this error: Uncaught TypeError: Cannot read property 'reset' of null

Where am I wrong here ?

like image 640
shri_wahal Avatar asked Jun 26 '15 02:06

shri_wahal


People also ask

How do you fix Typeerror Cannot read properties of null?

To solve the "Cannot read property 'value' of null" error, make sure you aren't accessing the value property on a null value, e.g. a non-existent DOM element. An element with the provided id does not exist in the DOM, so the getElementById method returns null .

Can not set property of null?

To solve the "Cannot set property 'value' of null" error, make sure that the DOM element you are accessing exists. The error is often thrown when trying to set a property after using the getElementById() method and passing it a non-existent id. Copied! const input = document.

What does Cannot read property ID of null mean?

If the error message says "Could not read property 'id' of null" it means that the guild property exists, but it is null.


1 Answers

Add id to your form:

<form id="form1" role="form" name="form1" action="reg_employer.php" method="post">

or

Try:

function ValidateEmail(inputText)
{
  var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  if(inputText.value.match(mailformat))
{
  document.form1.coemail.focus();
  return true;

}
else
{
  alert("You have entered an invalid email address!Enter again");
  document.form1.reset();   //<== change this line, use form name
  return false;
}
}
like image 183
Ajay Narain Mathur Avatar answered Nov 01 '22 07:11

Ajay Narain Mathur