user3917316
user3917316

Reputation: 11

create different forms based on option tag

I wasn't quite sure how to name this topic to resolve my problem so I apologize if it's somewhat of a duplicate question but this topic wasn't what I wanted.

I couldn't find a way to create a dynamic form that changes upon an option tag without having blank or undefined field that also gets sent via POST. In other words, is there anyway I can dynamically change the fields so that I don't have to send blank fields that are hidden away via .hide() in javascript? I set up a jsfiddle here with a possible scenario where I might run into similar fields in different options but also completely different fields in another option.

http://jsfiddle.net/boyilus/c0bdx8xL/

Here's an example of what I chose but doesn't quite do what I want: (full version in jsfiddle)

$('#companies').change(function(){
   selection = $(this).val();    
   switch(selection)
   { 
       case 'Microsoft':
           $('#microsoftType').show();
            $('#appleType').hide();
            $('#googleType').hide();
            $('#otherType').hide();     
           break;
       ......
       ......
    }
 });

appreciate all the help! thank you in advance!

Upvotes: 1

Views: 98

Answers (2)

Eadel
Eadel

Reputation: 3997

You can disable other fields in the form by marking them with disabled or disabled="disabled" attribute. Data from these controls will not be sent within the request. Something like the following:

switch(selection)
{ 
   case 'Microsoft':
       $('#microsoftType').show();
       $("#microsoftType input, #microsoftType textarea").removeAttr('disabled');
       $('#appleType').hide();
       $("#appleType input, #appleType textarea").attr('disabled', 'disabled');
       $('#googleType').hide();
       $("#googleType input, #googleType textarea").attr('disabled', 'disabled');
       $('#otherType').hide();
       $("#otherType input, #otherType textarea").attr('disabled', 'disabled');
           break;
       ......
       ......
}

Of course, it would be nice to move these hide/attr and show/removeAttr to separate functions. Hope it helps.

Upvotes: 0

Arnelle Balane
Arnelle Balane

Reputation: 5487

Try this one:

$('#companies').change(function(){
  selection = $(this).val();
  switch(selection) { 
    case 'Microsoft':
      $('#microsoftType').show().find('input, select, textarea').prop('disabled', false);
      $('#appleType, #googleType, #otherType').hide().find('input, select, textarea').prop('disabled', true);
      break;
   ......
   ......
  }
});

This takes advantage of the fact that disabled fields are not sent into the server once the form is submitted. You can refactor the code above and make it better, but that's the idea of how you can do it.

Upvotes: 1

Related Questions