How to Conditionally Show the Submit Button

Overview

Would you like to conditionally show the submit button on your form if a certain criterion has been met? You may want to just redirect a user to another page rather than submitting a form entry if they answer No to a particular question. Using PHP and JavaScript you can conditionally set up the submit button to show or hide based on an answer from your form.

Setup

1) Setting up the form

First, we’ll need to set up the conditions of the form. For this example, we’ve added a Multiple Choice field and only given it the values of Yes or No.

We’ve also created a page on our site called Thank You that if the user selects No on the form, they will be taken to a Thank You page and the form entry will not be submitted.

Set the multiple choice questions up on your form

2) Adding the code

To conditionally show the submit button based on your form answer, simply copy this code to your site.

In our code example below, we’re targeting the form ID 612.

add_action( 'wp_head', function () { ?>
	<style>
		.wpforms-form .wpforms-submit-container .wpforms-submit {
			visibility:hidden;
		}
		.wpforms-form .wpforms-submit-container .wpforms-submit.show-submit {
			visibility:visible;
		}
	</style>
<?php } );


// Conditional logic for Submit button
function wpf_dev_form_redirect() {
	?>
	<script>
		jQuery(function($){
			$("form#wpforms-form-612").click(function(){
				var selectedval = $(".wpforms-form input[type='radio']:checked").val();
				if(selectedval == "No"){
					window.location = "/thank-you";
				}
				if(selectedval == "Yes"){
					$(".wpforms-submit").addClass("show-submit");
				}
			});
		});
	</script>
	<?php
}
add_action( 'wpforms_wp_footer', 'wpf_dev_form_redirect' );

Remember to change the form-612 to match the form ID from your form as well as the window.location = "/thank-you"; to the slug name of the page you want the user redirected to if the answer is No.

The /thank-you is our site’s relative link. So if you created a page called Thanks, your window.location would be /thanks

Now you have completed how to conditionally show the submit button using the code above.

And that’s all you need to conditionally show the submit button on your form! Would you like to learn more about changing the color of the submit button? Take a look at our article on How to Change the Submit Button Color.