Conditional form with required field
-
Hey, I needed a form to have conditional fields and wanted these fields to be required. I finally managed to do it and will explain how I did. That might save a precious time so someone.
First of all, I followed this tutorial but for some reason, it didn’t work for me. Also this post is a bit old, it needed to be refreshed.
Step 1: Creating your form
Here is the code I used for the example : pastebin
I just created a simple form with a radio button and 2 text input.
The text inputs are wrapped in a div. The second text input div is hidden and have a default value. Also note both inputs are required !
If your theme doesn’t use bootstrap / foundation / …, just add this before your form :<style>.hidden{display:none}</style>
Step 2: Using jQuery to hide/show div
Here is the code I used : pastebin – conditionalRequired.js
I commented all the script, it should be enough to understand if you want to adapt it to your code ??
add it in a file nammed conditionalRequired.js to follow the example.Step 3: Include jQuery in your site
Upload the conditionalRequired.js file in your theme folder, in a js directory.
If you theme already use jQuery, you just need to include this script.
Some ppl recommend to add it in header.php, I did it in functions.php.
I also recommend you to load it only on your contact page.if (is_page( 'Contact' )){ wp_enqueue_script( 'conditionalRequired', get_template_directory_uri() . '/js/conditionalRequired.js', array(), '', true ); }
If needed, read more on the is_page() function here.
If you theme doesn’t have jQuery yet, download it here and also include it like above.
Some explanations:
TL;DR How it works : 1 radio button and 2 input fields. The fist input is shown, and the first tick of the radio button is default choice. The second input is hidden. Both input are required*. The second input has a default value.
When switching radio, the script will hide all the div and show the selected one. It will set a value to the hidden fields and remove the one forced previously on the shown one, so the user can enter his value without any problem.This might not be the best solution, but it does the job very well.
I asked a question without any answer here. That’s why I use this kind of validation.Hope this will help
- The topic ‘Conditional form with required field’ is closed to new replies.