Thursday, 8 October 2015

Radio Buttons- Show / Hide Form Fields

I was working for doctor's appointment system and required to show / hide some fields depending on the session of appointment. I have searched the internet but couldn't find the proper solution or a tutorial for it. And then I developed my own code just by using JavaScript. I am just copy-pasting my code over here.

Example Form Code:

<table>
<tr class="t-time-pers">
  <td class="t-time">
     <label for="time">Session</label>
     <div class="form-item">
     <input type="radio" id="morning1" name="session" value="Morning" checked>Morning <br/>
     <input type="radio" id="evening1" name="session" value="Evening">Evening
      </div>
    </td>
</tr>
<tr class="t-time-pers">
    <td class="t-time">
       <label for="time">Session</label>
          <div class="form-item" id="morning">
            <select name="time" id="morning" required>
               <option value="10.00 AM - 10.30 AM">10.00 AM - 10.30 AM</option>
               <option value="10.30 AM - 11.00 AM">10.30 AM - 11.00 AM</option>
       <option value="11.00 AM - 11.30 AM">11.00 AM - 11.30 AM</option>
               <option value="11.30 AM - 12.00 AM">11.30 AM - 12.00 PM</option>
      </select>
</div>
<div class="form-item" id="evening">
    <select name="time" id="evening" required>
        <option value="10.00 AM - 10.30 AM">04.00 PM - 04.30 PM</option>
         <option value="10.30 AM - 11.00 AM">04.30 PM - 05.00 PM</option>
 <option value="11.00 AM - 11.30 AM">05.00 PM - 05.30 PM</option>
           <option value="11.30 AM - 12.00 AM">05.30 PM - 06.00 PM</option>
</select>
      </td>
 </tr>
</table>


AND Put this JAVASCRIPT IN FOOTER just before closing </body> tag


<script>
/*Developed by Bhushan Bagde */
/*Radio Buttons enable and disable*/
$(document).ready(function(){
 $("#morning").show();
   $("#evening").hide();
$("#morning1").on("change", function(){
   $("#morning").show();
   $("#evening").hide();
});

$("#evening1").on("change", function(){
   $("#morning").hide();
   $("#evening").show(); 
});
})
</script>

That's it. You are not required to change css and other things to make it work. I hope you will like my code. If you have any doubts you can comment it here.

Thank You

No comments:

Post a Comment