iCode iCode - 1 year ago 56
HTML Question

How to show form input fields based on select value?

I know this is simple, and I need to search in Google. I tried my best and I could not find a better solution. I have a form field, which takes some input and a select field, which has some values. It also has "Other" value. What i want is, If the user selects the Other option, I want to display a text field to specify that other. It should be hidden first and should pop up when user selects "Other". When user selects other options I want to hide it. How can I perform that using JQuery?

This is my JSP code

<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>

<div id="otherType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>

Now I want to show the DIV tag*(id="otherType")* only when the user selects Other.
I want to try JQuery. This is the code I tried

<script type="text/javascript"
<script src="jquery-ui-1.10.0/ui/jquery-ui.js"></script>


selection = $('this').value();
case 'other':
case 'default':


But I am not able to get this. What should I do? Thanks

Answer Source

You have a few issues with your code:

  1. you are missing an open quote on the id of the select element, so: <select name="dbType" id=dbType">

should be <select name="dbType" id="dbType">

  1. $('this') should be $(this): there is no need for the quotes inside the paranthesis.

  2. use .val() instead of .value() when you want to retrieve the value of an option

  3. when u initialize "selection" do it with a var in front of it, unless you already have done it at the beggining of the function

try this:

        if( $(this).val()==="other"){


UPDATE for use with switch:

     var selection = $(this).val();
    case "other":

UPDATE with links for jQuery and jQuery-UI:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​