How to create validation to ask if the user really wants to leave the page?

Asked

Viewed 431 times

3

I have a tab where the user will edit fields that are in a form. This data comes from the database. The user can edit them, however, in the end he can write (ie will write/update in the database) or else he can close.

I want to make sure that the user, if they make a mistake and click another menu link, or click back the page is asked if they want to leave the page without pressing the save button?

1 answer

2

Create a method to confirm the page output by passing the url as parameter:

function confirmar(url){
    event.preventDefault();  
    var resposta = confirm("Deseja mesmo sair da página?");
    if (resposta == true){
        location.top.href = url;
    }
}    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Then put it in the attribute onclick of the html tag.

  • I didn’t understand the part about putting onclick in the html tag attribute.... I have to put this in all links? : S

  • yes, something like this: <a href="index.html" onclick="confirm('index.html')">Index</a>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.