I recently fixed this issue for one of my clients. He is using Elementor Popup. The Elementor popup has a contact form as content. The contact form is a shortcode of Contact Form 7 plugins.
The form is rendered flawless & the fields are visible well. But when submitting the form. The Page is getting refreshed & close the popup box.
The form submission redirects the page to something like this. http://www.example.com/#wpcf7-f3641-o2
The form validations are not visible & the popup gets closed.
If you are facing the same issue, Here a code snippet to helps fix this issue.
Reason of the issue
The Contact Form 7 JavaScript initialization is done while the web page is loaded. The Elementor popup form is rendered after opening the popup. So we need to re-initialize the Contact Form 7 script.
How to add custom Javascript snippets to your current website
1. The easy and layman’s option is, to use the Elementor custom code feature. Please review the screenshot below for more clarity.
<script type='text/javascript'> /** Document ready. We are waiting for the full page load. */ jQuery( document ).ready( function() { /** Click on link or button that opens the popup. It contain "#elementor-action" in href. */ jQuery( document ).on( 'click', "a[href*='#elementor-action']", function () { /** Let's give the elementor some time to animate popup. */ setTimeout( function() { document.querySelectorAll(".elementor-popup-modal form.wpcf7-form:not(.elementor)"). forEach((e => { wpcf7.init(e), e.closest(".wpcf7").classList.replace("no-js", "js"), e.closest(".wpcf7").classList.add("mystyle"); })); }, 800 ); // END Timeout. } ); // END link click. } ); // END Document ready. </script>
2. Use the wp_footer hook. https://developer.wordpress.org/reference/hooks/wp_footer/
<?php function prefix_contact_form_custom_js() { ?> <script type='text/javascript'> /** Document ready. We are waiting for the full page load. */ jQuery( document ).ready( function() { /** Click on link or button that opens the popup. It contain "#elementor-action" in href. */ jQuery( document ).on( 'click', "a[href*='#elementor-action']", function () { /** Let's give the elementor some time to animate popup. */ setTimeout( function() { document.querySelectorAll(".elementor-popup-modal form.wpcf7-form:not(.elementor)"). forEach((e => { wpcf7.init(e), e.closest(".wpcf7").classList.replace("no-js", "js"), e.closest(".wpcf7").classList.add("mystyle"); })); }, 800 ); // END Timeout. } ); // END link click. } ); // END Document ready. </script> <?php } add_action( 'wp_footer', 'prefix_contact_form_custom_js', 100 ); ?>
3. Add this script to your existing JS file, which I didn’t recommend. You must keep the custom code in a separate file and then enqueue that file into your active theme.
I hope it will perfectly work for you. Have a happy coding.