【问题标题】:Validation form - JS验证表格 - JS
【发布时间】:2017-11-06 03:08:29
【问题描述】:

有使用Bootstrap的评论表单

<!DOCTYPE html>
<html>
<head>
    <title>Comments</title>
</head>
<body>
    <form id="commentForm" name="commentForm" onsubmit="return(validate());">
        <div class="row">
            <div class="col-sm-12 form-group">
                <textarea class="form-control" id="comments" name="comments" placeholder="Leave comment..." rows="3"></textarea><br>
                <button class="btn pull-right" type="submit">Send</button>
            </div>
        </div>
    </form>
</body>
</html>

我写了一个 JS 验证

  <script type="javascript">
  function validate()
  {

     if( commentForm.comments.value == "" )
     {
        alert( "Please leave your comment!" );
        commentForm.comments.focus() ;
        return false;
     }
    </script>

它会检查一行是否为空,但它根本不起作用。请帮助我,我该如何解决?

【问题讨论】:

    标签: javascript html validation bootstrap-4


    【解决方案1】:

    将脚本标签的类型属性修复为text/javascript,并添加validate函数的遗漏}

    【讨论】:

      【解决方案2】:

      您必须像这样检索 commentForm 元素:

      function validate() {
        // Actually get the DOM element on which you can test value
        var commentForm = document.getElementById('commentForm');
        
        if (commentForm.comments.value === '') {
          window.alert('Please leave your comment!');
          commentForm.comments.focus() ;
          return false;
        }
      }
      <!DOCTYPE html>
      <html>
      <head>
        <title>Comments</title>
      </head>
      <body>
        <form id="commentForm" name="commentForm" onsubmit="return(validate());">
          <div class="row">
            <div class="col-sm-12 form-group">
              <textarea class="form-control" id="comments" name="comments" placeholder="Leave comment..." rows="3"></textarea><br>
              <button class="btn pull-right" type="submit">Send</button>
            </div>
          </div>
        </form>
      </body>
      </html>

      【讨论】:

        猜你喜欢
        • 2018-08-30
        • 2020-07-07
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 1970-01-01
        • 2019-06-27
        • 2019-09-25
        • 2023-03-14
        相关资源
        最近更新 更多