0

可能重复:
检测用户何时离开网页的最佳方法

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

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

在用户离开页面之前,是否有一种方法可以验证表单是否已提交?

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

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

接受我最大的尊重。

亲切的问候。

SP。

4

2 回答 2

3

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

于 2012-10-02T08:43:25.250 回答
0
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.
于 2012-10-02T09:10:27.593 回答