Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, a text field to specify that 'Other' should be displayed. When a user selects another option (than 'Other') I want to hide it again. 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>
</select>

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

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"
    src="jquery-ui-1.10.0/tests/jquery-1.9.0.js"></script>
<script src="jquery-ui-1.10.0/ui/jquery-ui.js"></script>
<script>    
$('#dbType').change(function(){

   selection = $('this').value();
   switch(selection)
   {
       case 'other':
           $('#otherType').show();
           break;
       case 'default':
           $('#otherType').hide();
           break;
   }
});
</script>

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

like image 737
iCode Avatar asked Mar 22 '13 09:03

iCode


1 Answers

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:

   $('#dbType').on('change',function(){
        if( $(this).val()==="other"){
        $("#otherType").show()
        }
        else{
        $("#otherType").hide()
        }
    });

http://jsfiddle.net/ks6cv/

UPDATE for use with switch:

$('#dbType').on('change',function(){
     var selection = $(this).val();
    switch(selection){
    case "other":
    $("#otherType").show()
   break;
    default:
    $("#otherType").hide()
    }
});

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>‌​
like image 176
DVM Avatar answered Oct 08 '22 02:10

DVM