skip to Main Content

I recently coded an alert action for my forms in a WordPress site. It’s working, but unfortunately only for the first form. If there is more than one form in the page, it’s not getting triggered.

Is there any way to get it working for all forms of the page?

My code:

add_action( 'wp_footer', 'mycustom_wp_footer' );

function mycustom_wp_footer() {
    ?>
    <script type="text/javascript">
        var wpcf7Elm = document.querySelector( '.wpcf7' );
        wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
            //if ('563' == event.detail.contactFormId) {
                var idform = event.detail.contactFormId;
                alert (idform);
            //}
        }, true );
    </script>
    <?php
}

Form snippets:

[contact-form-7 id="556" title="test 1"]
[contact-form-7 id="563" title="test 2"]

2

Answers


  1. Chosen as BEST ANSWER

    This is the final code (credit to Chris G):

    add_action( 'wp_footer', 'mycustom_wp_footer' );
    
    function mycustom_wp_footer() {
        ?>
        <script type="text/javascript">
            var wpcf7Elm = document.querySelectorAll( '.wpcf7' );
            wpcf7Elm.forEach(function(formr){
            formr.addEventListener( 'wpcf7submit', function( event ) {
                    var idform = event.detail.unitTag;
                    alert (idform);
            }, false ); })
        </script>
        <?php
    }


  2. CF7 events bubble up through the document, so you can do something like this,

    let page = document.querySelector('body');
    page.addEventListener('wpcf7submit', function(e){
      let idform = e.detail.contactFormId;
      alert (idform);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search