Search code examples
javascriptwordpresshttp-redirectcontact-form-7

Contact Form 7 Redirect on Submit and if the first radio is checked


We fave a CF7 form http://prntscr.com/v3ijfm, http://prntscr.com/v3ilpi . Website url : https://loyard.it/

The task:

If the first radio button is clicked and form is submitted, redirect the user to url.

For other 2 radio buttons a plugin handles the task (After successful payment user is redirected).

I inserted the js in functions.php but it's not working .

add_action('wp_footer', 'redirect_cf7');

function redirect_cf7()
{
    ?>
<script>
document.addEventListener('wpcf7mailsent', function(event) {
    $('#PayMeth input[name="radio-809"]').change(
        function() {
            if (this.checked && this.value == 'Paga alla consegna') {
                location = 'https://www.google.md/';
            }
        });
}, false);
</script>

Any suggestions ? Thanks in advance !

Update: This works but the issue is its redirecting also for the other 2 radio buttons (

<script>
    $('body #PayMeth input[name="radio-809"][value="Paga alla consegna"]').attr('checked', true).change(
        document.addEventListener('wpcf7mailsent', function(event) {
            window.location.href = 'https://loyard.it/thank-you/';
        }, false));
    </script>

Solution

  • f***ck this jQuery :P for me this is cleaner

    const redirect = () => {
       window.location.href = 'https://loyard.it/thank-you/';
    };
    
    const input = document.querySelector(`body #PayMeth input[name="radio-809"][value="Paga alla consegna"]`);
    //console.log(input) - check that your selector works correctly
    if(input){
      input.addEventListener("change", (event) => {
        if(event.target.value){
          document.addEventListener('wpcf7mailsent', redirect);
        } else {
          document.removeEventListener('wpcf7mailsent', redirect);
        }
      })
    }