Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Så här visar du popup för bekräftelse av navigation för formulär i WordPress

Det är irriterande att av misstag stänga en page utan att ha submittat your comment eller med ett halvfyllt formulär. Senast frågade en av våra användare oss om det var möjligt att visa sina läsare en popup för bekräftelse av navigation.

Den här lilla popupen alertar användarna och förhindrar att de av misstag lämnar halvfyllda och oskickade formulär. Det är ett bra sätt att förbättra användarupplevelsen och förhindra att visitorerna måste börja om från scratch.

I den här artikeln kommer vi att visa dig hur du visar popup för bekräftelse av navigation för WordPress formulär.

Confirm navigation popup when user leaves a form unsubmitted

Vad är en popup för bekräftelse av navigation?

Låt oss anta att en användare skriver en comment på din blogg. De har redan skrivit en hel del rader, men de blir distraherade och glömmer att submit kommentarer. Nu, om de stänger sin webbläsare, kommer kommentaren att gå förlorad.

Popupen för bekräftelse av navigation ger dem en chans att slutför sin comment.

Du kan se den här funktionen i action på WordPress post editor vy. Om du har unsaved ändringar och du försöker lämna page eller close webbläsaren, kommer du att se en varning popup.

Unsaved changes warning popup in WordPress post editor

Låt oss se hur vi kan lägga till denna varningsfunktion till WordPress comments och andra formulär på din site:

Visa popup för bekräftelse av navigation för ej inskickade formulär i WordPress

För denna tutorial kommer vi att skapa ett custom plugin, men oroa dig inte, du kan också ladda ner plugin i slutet av denna tutorial för att installera på din webbplats.

Men för att få en bättre förståelse för koden ber vi dig att försöka skapa ditt eget plugin. Du kan göra detta på en lokal install eller en staging site först.

Låt oss komma igång.

Först måste du skapa en new folder på din dator och döpa den till confirm-leaving. Inuti mappen confirm-leaving måste du skapa en annan folder och döpa den till js.

Öppna nu en plain text editor som Notepad och skapa en new fil. Inuti klistrar du helt enkelt in följande kod:

[php]
<?php
/**
 * Confirm Leaving
 * Plugin Name: Confirm Leaving
 * Plugin URI:  https://www.wpbeginner.com
 * Description: This plugin shows a warning to users when try they forget to hit submit button on a comment form.
 * Version:     1.0.0
 * Author:      WPBeginner
 * Author URI:  https://www.wpbeginner.com
 * License:     GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 */

function wpb_confirm_leaving_js() { 

     wp_enqueue_script( 'Confirm Leaving', plugins_url( 'js/confirm-leaving.js', __FILE__ ), array('jquery'), '1.0.0', true );
}
add_action('wp_enqueue_scripts', 'wpb_confirm_leaving_js');
[/php]

Denna PHP-funktion addar helt enkelt en JavaScript-fil till front-enden på din website.

Gå vidare och save denna fil confirm-leaving .php i huvud confirm-leaving folder.

Nu måste vi skapa den JavaScript-fil som detta plugin hämtar.

Skapa en new fil och klistra in den här koden i den:

[javascript]
jQuery(document).ready(function($) { 

$(document).ready(function() {
    needToConfirm = false;
    window.onbeforeunload = askConfirm;
});

function askConfirm() {
    if (needToConfirm) {
        // Put your custom message here
        return "Your unsaved data will be lost.";
    }
}

$("#commentform").change(function() {
    needToConfirm = true;
});

 })
[/javascript]

Denna JavaScript-kod upptäcker om användaren har unsaved ändringar i formuläret för kommentarer. Om en användare försöker navigera bort från page eller close fönstret visas en popup med en varning.

Du måste spara den här filen som confirm-leaving.js i mappen js.

När du har saved båda filerna, är det så här din folder struktur ska gilla att se ut:

Plugin file structure

Nu måste du ansluta till din WordPress site med hjälp av en FTP-klient. Se vår guide om hur du använder FTP för att uploada WordPress-filer.

När du har anslutit dig måste du uploada confirm-leaving mappen till /wp-contents/plugins/ mappen på din website.

Uploading plugin files to your WordPress site

Efter det måste du logga in i WordPress admin area och besöka Plugins page.

Leta reda på tillägget ”Confirm Leaving” i listan över installerade plugins och klicka på länken ”activate” under det.

Activate plugin

Det är all. You can now visit any post on your website, write some text in any field of the comment form, and then try leaving the page without submitting.

En popup visas som varnar you för att du är på väg att lämna en page med unsaved ändringar.

popup notification warning user about unsaved changes

Lägga till varningen i andra formulär i WordPress

Du kan använda samma kodbas för att rikta in dig på alla formulär på din WordPress site. Här visar vi dig ett exempel på hur du använder den för att rikta in dig på ett kontaktformulär.

I det här exemplet använder vi WPForms plugin för att skapa ett kontaktformulär. Instruktionerna kommer att vara desamma om du använder ett annat plugin för kontaktformulär på din website.

Gå till den page där du har addat ditt kontaktformulär. För muspekaren till det första fältet i ditt kontaktformulär, högerklicka och välj sedan ”Inspect” i webbläsarens menu.

Finding form ID

Locate the line that starts with the <form> tag. I formuläret taggen hittar du ID-attributet.

I det här exemplet är vårt formulärs ID:n wpforms-form-170. Du måste kopiera attributet ID:n.

Edit nu filen confirm-leaving.js och add to ID:n efter #commentform.

Se till att du separerar #commentform ditt formulärs ID:n med ett kommatecken. You will also need to add a # sign as a prefix to your form’s ID:n attribute.

Din kod kommer nu att se ut så här:

[javascript]
jQuery(document).ready(function($) { 

$(document).ready(function() {
    needToConfirm = false;
    window.onbeforeunload = askConfirm;
});

function askConfirm() {
    if (needToConfirm) {
        // Put your custom message here
        return "Your unsaved data will be lost.";
    }
}

$("#commentform,#wpforms-form-170").change(function() {
    needToConfirm = true;
});

 })
[/javascript]

Save your changes and upload the file back to your website.

Nu kan du enter valfri text i valfritt fält i ditt Contact Form och sedan försöka lämna page utan att submit formuläret. En popup kommer att visas med en varning om att du har unsaved ändringar.

Du kan downloada confirm-leaving plugin här. Det riktar sig bara till formuläret comment, men du får gärna editera pluginet för att rikta det mot andra formulär.

Det var all; vi hoppas att den här artikeln hjälpte dig att visa popupen för bekräftelse av navigation för WordPress-formulär. Du kanske också vill kontrollera våra tillägg och tools för WordPress som du måste ha för webbplatser för företag eller läsa vår ultimata guide om hur du ökar trafiken till din blogg.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

20 kommentarerLämna ett svar

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Igor says

    Tried to use your code in bbpress forum. Unfortunately no popup message appears after user dose not post his comment. Tried all variations of changing id in JS file but still nothing appears.

  3. Bob Garrett says

    Further to my previous query I have now tried using the form’s parent div id and modified the code. This almost works but…

    The text shown by the pop-up is not the text entered in the code.

    Even if the form is completed and submit hit, then going to another page still results in the warning.

    How can I resolve this?

  4. Tom Kelley says

    Have tried this vvvvv to no avail. Working with Gravity Forms. All else works well, but the warning still comes up when hitting the submit button on a completed form. Any advice?

    WPBeginner Support
    Nov 27, 2016 at 6:52 am

    Hi Bonnie,

    We tested the plugin with WPForms and it worked. You will need to edit the confirm-leaving.js file and replace #commentform with the wpforms container div id. Typically it is wpforms-12 where 12 is the ID of your form. You can also see it using the inspect element tool in your browser.

    • Bonnie Ramthun says

      I’m still trying to figure out how to make sure the popup DOESN’T appear when the user presses the ”Submit” button. The confirm leaving popup shouldn’t appear if the user has entered all the information required, but this code makes it pop up every time.

      I would so appreciate the help, if there is a solution available.

  5. Swayam Dhawan says

    I Need the same function when someone navigate from particular page in website and while click on stay , they must navigate to home page of the website.

    waiting for the response.

  6. Bonnie Ramthun says

    I am so happy for your wonderful confirm navigation code! I need it desperately because many of my clients users can’t get it through their head that they need to press the ”Submit” button on the form.

    The code works perfectly, except for one problem. When I press the ”Submit” button on my WPForms form, the confirm navigation code pops up. I would like the ”confirm navigation” to happen only when the user doesn’t press the ”Submit” button. I can’t figure out how to do this. Can you help?

    • WPBeginner Support says

      Hi Bonnie,

      We tested the plugin with WPForms and it worked. You will need to edit the confirm-leaving.js file and replace #commentform with the wpforms container div id. Typically it is wpforms-12 where 12 is the ID of your form. You can also see it using the inspect element tool in your browser.

      Administratör

  7. Will C says

    I have two separate multi-page gravity forms on my site. When this plugin is active, I get a confirmation popup when clicking ”Next Step” on one of the forms (undesired), but not the other. Are you aware of any issues with gravity forms and ”window.onbeforeunload”? Thanks

      • Nipa Sarker says

        I ma using the code for buddy-press multi step create group from.It is working fine except while clicking on the next step button or save button it is showing the same alert.
        I ma using the form id ”#create-group-form” instead of the #commentform

  8. Luis Zarza says

    Hi, nice post!

    It helped a lot. But your solution won’t work while logged in. It only works for users that fill in the form and are logged out. I need it also to work for logged in users, please!
    Could you provide a solution for that?

    Thanks.

    • Luis Zarza says

      Sorry, it does actually works when you create the plugin. At first I did it only throwing the JS to the page I wanted without creating the plugin, because I didn’t want the script to be loaded on all the pages of my site.

    • WPBeginner Support says

      Contact Form 7 uses an ID with all the forms. The line that contains form ID will look something like this:

      <div role="form" class="wpcf7" id="wpcf7-f85-p11-o1" lang="en-US" dir="ltr">
      

      In this example, the form’s ID attribute is wpcf7-f85-p11-o1. Hope this helps.

      Administratör

  9. Betty L Van Fossen says

    I have two problems. One I get these pop up in my mail all the time,q it’s aggravating. I’m 89 in yrs.therefore a little short on patience and I start using my pointer to fast hitting other things, so I get myself in lots of problems. Two –guess(I know) I have to many cookies they say. What are the cookies –how do I eleminate them? What do you mean subscribe without commenting. I prefer the e-mail. O.K..to personal and meaningful conversation.

        • Betty L Van Fossen says

          Safari said I could not get in cause I had to many cookies. In the meantime I was on my e-mail and the pop ups came on, while on my e-mail they are always popping up. I got on google and asked for help on cookies and pop ups and gave me lots to choose from. Now word press got in here, what is word press. I’m not going to write a book,just NEED HELP. Answer by e-mail. I’m turning you off now I’m really tired now.

Lämna ett svar

Tack för att du väljer att lämna en kommentar. Tänk på att alla kommentarer modereras enligt våra policy för kommentarer, och din e-postadress kommer INTE att publiceras. Vänligen använd INTE nyckelord i namnfältet. Låt oss ha en personlig och meningsfull konversation.