【问题标题】:how to make a form be validated before user will quit the page [duplicate]如何在用户退出页面之前验证表单[重复]
【发布时间】:2012-09-23 02:41:48
【问题描述】:

可能重复:
Best way to detect when user leaves a web page

我正在寻找一种功能,它可以确保在用户离开页面之前表单已经过验证。

实际上我为必填字段添加了许多必填项,但没有什么可以确保表单将被验证。

有没有办法在用户离开页面之前验证表单是否已提交?

其实我用的是onclick='return confirm ("Do you really want to go out of the page ?")'

但是没有什么可以验证表单是否已经提交。

接受我最大的尊重。

亲切的问候。

SP。

【问题讨论】:

    标签: javascript forms submit verify


    【解决方案1】:

    为什么不在提交表单的时候返回一个值或者设置一个隐藏字段,然后在用户离开的时候用JS检查这个值呢?这不会阻止用户只是关闭原因窗口,而是一个开始。

    【讨论】:

      【解决方案2】:
      There is onsubmit event on the form that accepts either true or false 
      
      You can attach it to a function that return either true or flase
      
      Example :
      
      
      html form
      
        <form name="myForm" action="test.html" onsubmit="return validateForm()" method="post">
              name:
      
      
              <input type="text" name="fname" />
      
      
      
              <input type="submit" value="Submit" />
          </form>
      
      
      Java Script Code
      
      
          <script type="text/javascript">
      
              function validateForm() {
                  var x = document.forms["myForm"]["fname"].value;
                  if (x == null || x == "") {
                      alert("First name must be filled out");
                      return false;
                  }
                  else {
      
                      return true;
                  }
              }
          </script>
      
      
      if you leave the name empty : it will alert you
      
      if not it will go to test.html
      
      Hope this is helpful.
      

      【讨论】:

      • 尊敬的先生,感谢您的回复。实际上,我不是在寻找验证表单,我的意思是我使用属性 required="true" 来告知需要填写哪些输入。实际上,如果有人在未提交表单的情况下离开页面,我想显示警报
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      相关资源
      最近更新 更多