Exit confirmation message

Asked

Viewed 50 times

0

I am working with creating documents, where the user enters with the information so that the document can be generated. I would like if the user had already written something in any of the fields and clicked to exit the page, an output confirmation message would appear on the screen. I read about other topics here and found out onbeforeunload of Javascript, however, I found nothing talking about how to make the message appear only if there is something in the fields. My code is like this:

<script language="JavaScript">
    window.onbeforeunload = confirmExit;
    function confirmExit(){
        if((document.getElementsByName("interessado").value != "")||
           (document.getElementsByName("assunto").value != "")||
           (document.getElementsByName("assinatura").value != "")){
                return "Deseja realmente sair?";
        }
    }

How can I create an output confirmation message only if there is some information in the text fields?

  • 1

    Just count it, pick it up input (ex), and makes a length, ai if it is larger than one, you warn (call the function), otherwise...

  • You think you’re more efficient than the method Lucas quoted below?

  • 1

    I think it doesn’t change much, since the concept is the same, then it will depend on what you think best, I especially usually count, but the two solutions will bring a very similar result

1 answer

1


getElementsByName returns an array, so you need to check the index:

function confirmExit(){
    if( ( !document.getElementsByName("interessado")[0].value )||
        ( !document.getElementsByName("assunto")[0].value )||
        ( !document.getElementsByName("assinatura")[0].value )){
            return "Deseja realmente sair?";
    }      
}
  • The part of the fields worked, but when I click on the send button the message appears. You can help me?

  • 1

    Sure, but it’s so the message doesn’t show up?

  • When I click the send button, the user is redirected to the generated document. I would like it not to appear in this case.

  • 1

    In the test I did appeared the confirmation dialog before the redirect metho @Lucasramos

  • Yeah, but I wish he wouldn’t show up on this case, you know,?

  • If the user leaves the page or clicks the back button, the information is not yet saved, so there is a risk of losing it. But when he clicks the send button, the information goes straight to the bank, so you risk losing it.

Show 1 more comment

Browser other questions tagged

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