0

Possible Duplicate:
Best way to detect when user leaves a web page

I'm looking for a function that will make sure that a form has been validated before the user will go out of the page.

Actually I added many required for the required fields but there is nothing to make sure that the form will be validated.

Is there a way or something that will verify if a form has been submitted before the user will go out of the page?

Actually I use the onclick='return confirm ("Do you really want to go out of the page ?")'

But there is nothing to verify if the form has been submitted.

Receive all my utmost RespecT.

Kind regards.

SP.

Community
  • 1
  • 1
Stanislas Piotrowski
  • 2,595
  • 10
  • 40
  • 59

2 Answers2

3

Why don't you return a value or set a hidden field when the form is submitted and then check this value with JS when the user leaves? This doesn't prevent the user from just closing the window of cause, but is a start.

Rainer.R
  • 458
  • 2
  • 8
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.
user123456
  • 2,524
  • 7
  • 30
  • 57
  • Dear Sir Thanks for your reply. Actualy I'm not looking for validating form I mean I use the attribute required="true" to inform which input are necessaryu to be filled. Actually I would like to display an alert if somebody leave the page without submiting the form – Stanislas Piotrowski Oct 02 '12 at 09:23