Show/Hide form field selecting a radio button option

It is possible to display a particular (or more) hidden fields when you site visitor chooses an option from a radio button. In this example, I will show how to display an email address field (which is hidden) once you click on "Yes, I want to subscribe" radio button with the help of css and jQuery.

Preview

show-hide-toggle-form-field-upon-selecting-a-radio-button-option

HTML + jQuery

We will have our form inside a container with ID 'myform'. Notice the onclick attribute on radio buttons. You will see that I have placed some javascript there. They will take care the toggling (show/hide) of the email address input field.

  1.  
  2. <div id="myform">
  3.   <h3>Do you want to subscribe to our newsletter?</h3>
  4.  
  5.   <form>
  6.     <input onclick="javascript: $('#email').show('slow');" type="radio" name="subscribe" value="1" />
  7.     <label>Yes, I want to subscribe</label>
  8.     <br />
  9.  
  10.     <input onclick="javascript: $('#email').hide('slow');" type="radio" name="subscribe" value="0" />
  11.     <label>No, thanks</label>
  12.     <br />
  13.  
  14.     <div id="email">
  15.       <label>Email Address: </label>
  16.       <input name="email" type="text" />
  17.     </div>
  18.   </form>
  19. </div>

Must remind you to link to jQuery library in your HEAD tag.

CSS

We start by defining some properties for our container.

  1. #myform {
  2.   padding: 10px;
  3.   background-color: #eee;
  4.   width: 400px;
  5.   border: 1px solid #ccc;
  6. }
  7.  
  8. #myform h3 {
  9.   font-weight: normal;
  10. }

Time for some labels and inputs (form elements).

  1. #myform label {
  2.   font-size: 18px;
  3. }
  4.  
  5. #myform input[type=text] {
  6.   font-size: 20px;
  7.   width: 200px;
  8. }

Email address field should be hidden when your document loads in a browser

  1. #email {
  2.   margin: 20px 0px 0px 0px;
  3.   display: none;
  4. }

Okay, everything done now. Open your webpage in a browser and see yourself!

Share: