Last Updated on September 20, 2022 by Roshan Parihar
In this tutorial, learn how to show hide input fields based on radio button selection using jQuery. The short answer is to use the show()
to show the input fields and hide()
to hide the input fields.
You can display input fields based on the radio button your user select. It is useful to get the required data according to the selection of users. Let’s find out with the example given below.
How to Show Hide Input Fields Based on Radio Button Selection in jQuery
You have to first hide the input fields using the CSS display:none
property. After that, use the show()
to display the required input fields and hide()
hide the non-required input fields.
See the script given below to understand the use of class and ids of the div
elements. It is useful to display the input fields according to the radio button selection.
1 2 3 4 5 |
<style> .myDiv{ display:none; } </style> |
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('input[type="radio"]').click(function(){ var demovalue = $(this).val(); $("div.myDiv").hide(); $("#show"+demovalue).show(); }); }); </script> |
1 2 3 4 5 6 7 8 9 10 11 12 |
<input type="radio" name="demo" value="One"/> Name <input type="radio" name="demo" value="Two"/> Email <input type="radio" name="demo" value="Three"/> Phone Number <div id="showOne" class="myDiv"> <input type="text" placeholder="Enter your name"> </div> <div id="showTwo" class="myDiv"> <input type="email" placeholder="Enter your email address"> </div> <div id="showThree" class="myDiv"> <input type="tel" placeholder="Enter your phone number"> </div> |
Output
Name
Email
Phone Number
The above example contains the three radio buttons with their matching input fields to display when someone selects the radio buttons.
When the user selects the name radio button, they will get the name input field. If they select the email radio button, they will get the email input field. Similarly, when they select the phone radio button, they will get the phone input field to enter their phone number.
You May Also Like to Read