Show input field based on select value – jQuery

How can you show or hide an input field based on a select value in a HTML form? That’s easy with jQuery.

Let’s say you have a form where the user can select a district:

and if their district is not in the list, the form shows a field to add a new district (note: this tutorials does not talk about saving the values in a database):

First, let’s create a simple HTML form:

 

<h2>Select a district</h2>
<form method="post">
 <table cellpadding="2" cellspacing="2" border="1">
  <tr>
	<td bgcolor="#999">District:</td>
	<td>
            <select name="district" id="district">
		<option value="district1">district 1</option>
		<option value="district2">district 2</option>
		<option value="other">other</option>
	    </select>
	</td>
   </tr>
   <tr id="otherdistrict">
	<td bgcolor="#999">Other district:</td>
	<td><input  name="otherdistrict" type="text" value="add district"></td>
   </tr>
   <tr>
	<td colspan="2" align="center"><input type="submit" value="save"></td>
   </tr>
 </table>
</form>

Now, what we have to do first is to read the value of the select. The select has the id=”district” so let’s write a little code to read what value is selected:

<script>
 jQuery(function() {
     
    var District = jQuery('#district');
   
 });
</script> 

So now, the var District holds the selected value. As the otherdistrict fields are visible by default when the page loads, we should check if the page opens with the selected “other”. If the select is not set on “other” we should hide the otherdistrict fields:

if (District.val()!="other") {
    	jQuery('#otherdistrict').hide();
    }

As a final step we should handle what happens with the otherdistrict fields when the user changes the selected value. To do this we will use the “change” event and show or hide the fields accordingly:

var select = this.value;
	District.change(function () {
    if (jQuery(this).val() == 'other' ) {
    	
        jQuery('#otherdistrict').show();
        
    }
    else { jQuery('#otherdistrict').hide();} 
});

That’s it! Now the otherdistrict fields should show or hide on page load or user select.