1

I am looking for a way to add conditional logic to a CF7 form. I've stumbled upon a few plugins but those that I found seem to be missing the functionality that I am looking for.

I am looking to change the value of a hidden field based on condition of a drop-down menu.

Example use cases:

If language-drop-down = "Spanish" Set textfield1 to "/filedirectory/for/spanish/templatefile"

If video-type-drop-down = "Open house promotion" Set textfield2 to "view"

I hope someone can point me in the right direction in order to implement this.

With kind regards, Danny

1

The only way to achieve this is to use a custom script file.

Load the script on the page where your form is being loaded using the following back-end function in your functions.php file,

add_action( 'wp_enqueue_scripts','register_custom_script');
//its important to register the script, else it will not load properly.
function register_custom_script(){
   wp_register_script( 'custom-cf7-script', <url to your script file>, array( 'jquery' ), null, true );
}
add_filter( 'do_shortcode_tag','load_custom_script', 10,3);
function load_custom_script($output, $tag, $args){
    if('contact-form-7' != $tag){
      return $output; //not a cf7 form shortcode.
    }
    if(!isset($attr['id']) || <yourform-id> != $attr['id']){
      return $output; //not your form
    }
    //load your custom script that you previously registered.
    wp_enqueue_script( 'custom-cf7-script');
}

in your custom script you'll want to do something like,

(function($){
  $(document).ready(function(){
    var $select = $('#language-drop-down');
    var $hidden = $('#textfield1');
    $select.on('change',function(){
      if("spanish"==this.value) $hidden = "/filedirectory/for/spanish/templatefile";
    });
  })
})(jQuery)
  • 1
    Thank you so much for taking the time to write down this comprehensive answer. I was reading up on JavaScript last night and I was taking it in a different direction, by editing the html source of the and adding / setting variables in there. That would have made it much harder to make edits to the form if needed though. Not being a web developer, I never would have came to solution like the one you've posted. I am able to follow the code logic however and I think I'll manage to make the required adjustments to make it work for my forms. Thank you so much! Danny – Danny Basting Nov 8 '19 at 19:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.