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"]
CodePudding user response:
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
}
CodePudding user response:
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 = event.detail.contactFormId;
alert (idform);
});