未捕获的类型错误:无法在 Javascript 中读取 null 的属性“重置”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31063919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:11:46  来源:igfitidea点击:

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

javascripthtmlvalidation

提问by shri_wahal

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

单击“下一步”按钮时,我会正确收到一条警报消息,但之后它会重定向到下一页,而不是重置当前页面。在 chrome 的控制台中检查元素时,我发现了这个错误: Uncaught TypeError: Cannot read property 'reset' of null

Where am I wrong here ?

我哪里错了?

采纳答案by Ajay Narain Mathur

Add idto your form:

添加id到您的表单:

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

<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;
}
}

回答by shri_wahal

Apparently I didn't have a form id in

显然我没有表单 ID

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

Addition of a form id resolved the issue . Quite a silly mistake on my part.

添加表单 ID 解决了该问题。就我而言,这是一个相当愚蠢的错误。