简体   繁体   中英

Contact form 7 validation error in popup

** UPDATE ** Right, I have been playing around a bit and I noticed that the form .wpcf7-form gets a class invalid when some fields are missing. So what i would like is when the class invalid is added an alert will popup. This is my code so far:

    $(document).ready(function(){

    $('form.wpcf7-form').click(function(){    
        if ($(this).hasClass('invalid')) {
            alert('Error Mess.');
        }
    });
}

The only problem now is, that I've been getting the error:

13:17:24.023 SyntaxError: expected expression, got ')'

Where is this missing?

I've been trying to get this working for some time now. I would like to have the validation errors that contact form 7 gives in a pop-up. Why, because the validation error below the button breaks my page style.

I have tried to position the validation error using CSS, this sort of works. But the error keeps being displayed over the contact form then, and there is no way to get it out of the way (click or otherwise).

I know you can place additional information like javascript (on_send_ok:"alert(Your message)" But what value is used for the validation error?

I also know there are some plugins around for this "problem" but most of them haven't had support for over 2 years and I would like to avoid using plugins as much as possible.

Thanks.

You can achieve this using one of the dom events called 'wpcf7submit' available in Contact Form 7.

"wpcf7submit — Fires when an Ajax form submission has completed successfully, regardless of other incidents."

This event will fire when a validation error occurs as well.

For example, if you want to show popup for a required field which has ID 'txt_name' you will add this code under your theme's functions.php file:

<?php
function conactform_validation_error_popup() {
?>
    <script type="text/javascript">
        document.addEventListener( 'wpcf7submit', function( event ) {
            if ( '4' == event.detail.contactFormId ) { // your contact form ID
                if(event.detail.status = 'validation_failed'){ // if validation fails
                    var invFields = event.detail.apiResponse.invalidFields;
                    jQuery.each(invFields, function(key, obje){
                        if(obje.idref == 'txt_name'){
                            alert('Please add a name.');
                        }
                    });
                }
            }
        }, false );
    </script>
<?php
}
add_action( 'wp_footer', 'conactform_validation_error_popup' );
?>

Below images explain how it works.

Steps shown in code

Steps shown in result JSON

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM