使用事件监听器提交表单

时间:2018-07-06 03:50:36

标签: javascript forms

我有这个表格:

<form name="form" action="#">
  <h1>Contact</h1>
  <div>
    <label for="name">Name:</label>
    <span id="error_name"></span>
    <input type="text" name="user_name" id="name">
  </div>
  <div>
    <label for="mail">E-mail:</label>
    <span id="error_email"></span>
    <input type="email" name="user_mail" id="mail">
  </div>
  <div>
    <label for="msg">Message:</label>
    <span id="error_msg"></span>
    <textarea name="user_message" id="msg"></textarea>
  </div>
  <input type="submit" name="submit">
</form>

并且我尝试不使用onsubmit =“ returnvalidation()”来提交表单,我想使用addEventListener来做到这一点,但我没有这样做:

document.getElementById('form')。addEventListener('submit',validate);

function validate() {
    var name = document.getElementById('name').value;
    var email = document.getElementById('mail').value;
    var message = document.getElementById('msg').value;
    if (name == "" || email == "" || message == "") {
        var error = document.createElement('p').textContent = "*This Field is Required";
        document.getElementById('error_name').innerHTML = error;
        document.getElementById('error_email').innerHTML = error;
        document.getElementById('error_msg').innerHTML = error;
        event.preventDefault();
    }
}

它返回无法读取null的属性'addEventListener',我如何使其工作并通过addEventListener提交?

1 个答案:

答案 0 :(得分:0)

您正在尝试通过“ id”形式获取元素,但没有“ id”“ form”形式的元素。

document.getElementById('form').addEventListener('submit', validate);

那你为什么不给这个表单一个ID

<form name="form" action="#" id='form'>

document.getElementById('form').addEventListener('submit', validate);

function validate() {
    var name = document.getElementById('name').value;
    var email = document.getElementById('mail').value;
    var message = document.getElementById('msg').value;
    if (name == "" || email == "" || message == "") {
        var error = document.createElement('p').textContent = "*This Field is Required";
        document.getElementById('error_name').innerHTML = error;
        document.getElementById('error_email').innerHTML = error;
        document.getElementById('error_msg').innerHTML = error;
        event.preventDefault();
    }
}
<form name="form" action="#" id="form">
  <h1>Contact</h1>
  <div>
    <label for="name">Name:</label>
    <span id="error_name"></span>
    <input type="text" name="user_name" id="name">
  </div>
  <div>
    <label for="mail">E-mail:</label>
    <span id="error_email"></span>
    <input type="email" name="user_mail" id="mail">
  </div>
  <div>
    <label for="msg">Message:</label>
    <span id="error_msg"></span>
    <textarea name="user_message" id="msg"></textarea>
  </div>
  <input type="submit" name="submit">
</form>