Saumya Majumder
Saumya Majumder

Reputation: 15

HTML Form field show/hide as per option selected from dropdown

Today I face another big problem on the way to developing my site. I have a normal form with some basic CSS. Now I want to use the form in that way, some fields will be hidden by default, the respective textfield will be activated as per menu selected from dropdown list. I first thought to do it it PHP in some other way but that will not be proper for my requirment. I want somecode which will act on that same page without refreshing. So I need some JavaScript or jQuery or Ajax work. But I'm not good in this languages so I need your help.

After doing huge googleing I find a piece of JavaScript code which is working for me. That is http://jsfiddle.net/ZxLU9/

But The problem is it is only working for two option as it was given on the site. I tried to add id3. But when ever I'm increasing an id, the code is not working anymore. Also, though this code is using tbody the hidden form design is totally broken. I'm sharing my full code here. Within the code there are some PHP code, ignore that, I'm not concern about that right now. Just fix me this issue with my actual design.
Please
You can visit the full code here : http://jsfiddle.net/QvJH6/2/

CHECK THE FIELD NAMED EXTRA . . . . That is the one where I want to put that code.

Upvotes: 0

Views: 3941

Answers (2)

saianirudh
saianirudh

Reputation: 104

//change the function call from

//onchange="display(this,'text','image');"

//to // onchange="display(this,'text','image',invisible);"

//and also change your display function in javascript to

function display(obj,id1,id2,id3) {
           txt = obj.options[obj.selectedIndex].value;
           document.getElementById(id1).style.display = 'none';
           document.getElementById(id2).style.display = 'none';
           document.getElementById(id3).style.display = 'none';
           if ( txt.match(id1) ) {
              document.getElementById(id1).style.display = 'block';
           }
           if ( txt.match(id2) ) {
              document.getElementById(id2).style.display = 'block';
           }
           if ( txt.match(id3) ) {
              document.getElementById(id2).style.display = 'block';
           }

}

Upvotes: 0

Alex Reynolds
Alex Reynolds

Reputation: 6352

Use Jquery change event.

 $('#select_box').change(function() {
   if($(this).val() == "somevalue"){
     if($(this).next('input').css("display") == "none"){
          $(this).next('label').show();
          $(this).next('input').show();
      //Code to hide any existing fields go here.
     }
   }
 });

That should work if you make everything consistent. If not then you will have to do one for each select box and specifiy which fields to show

Upvotes: 1

Related Questions