“必需”标签在第一次无法使用

时间:2019-06-20 13:03:22

标签: javascript html

我有一个网站,其中包含一个小表格。它只是询问电子邮件,姓名和一个小注释框。

几天前我添加了它,看到人们会随机单击它,并且我的收件箱中会收到空白的提交内容。

现在,我已经在所有三个HTML元素上添加了“必需”标签。那行得通...但是只有在第一次尝试通过之后...

能不能解释为什么会这样?

我已包含您的评论代码:

<form action="contactform.php" method="post">
              <div class="form-group">
                <label for="exampleInputEmail1">Email address</label>
                <input type="email" class="form-control" id="exampleInputEmail1" name="email" aria-describedby="emailHelp" placeholder="Enter your email" required>
                <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
              </div>
              <div class="form-group">
                <label for="nameofclient">Name</label>
                <input type="text" class="form-control" id="nameofclient" name="name" placeholder="Enter name" required>
              </div>
              <div class="form-group">
                  <label for="exampleFormControlTextarea1">Questions/Concerns</label>
                  <textarea class="form-control" id="exampleFormControlTextarea1" name="comment" rows="3" required></textarea>
                </div>
              <button type="submit" class="btn btn-primary">Submit</button>
            </form>

1 个答案:

答案 0 :(得分:0)

window.onload = function () {
  var form = document.getElementById('theForm');
  form.button.onclick = function (){
    for(var i=0; i < form.elements.length; i++){
      if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
        alert('There are some required fields!');
        return false;
      }
    }
    form.submit();
  }; 
};
<form action="contactform.php" method="post">
              <div class="form-group">
                <label for="exampleInputEmail1">Email address</label>
                <input type="email" class="form-control" id="exampleInputEmail1" name="email" aria-describedby="emailHelp" placeholder="Enter your email" required>
                <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
              </div>
              <div class="form-group">
                <label for="nameofclient">Name</label>
                <input type="text" class="form-control" id="nameofclient" name="name" placeholder="Enter name" required>
              </div>
              <div class="form-group">
                  <label for="exampleFormControlTextarea1">Questions/Concerns</label>
                  <textarea class="form-control" id="exampleFormControlTextarea1" name="comment" rows="3" required></textarea>
                </div>
              <button type="submit" class="btn btn-primary">Submit</button>
            </form>

上面的代码可能有帮助