Forums

Show/Hide fields based on drop down selection

tidusx18 24 Feb, 2009
Hi,

I am creating a site where users submit a request for various types of products and services. There are a lot of categories and I was wondering if I could make one big form and have some of the fields be shown only if the user selects the appropriate selection from a drop down box. If anything else is selected, the fields should not show. Also, The first field (the category field) should start the process (i.e. when the user first get to the form page all they see if the one drop down box to select a category).

Is there any simple way to do this...keeping in mind that I am a novice with code.

If this can be done, if a field is "required", but not displayed (hidden), will that not let the form submit?

I have a bunch of other questions, but I'll leave it at that (my main problem) for now lol.

Thanks a lot! πŸ˜€

Daniel.
Max_admin 24 Feb, 2009
Hi Daniel,

Is there any simple way to do this.



using JS, it depends on your form code, try to google "change element style using JS", you need to change the "display" css property of the element!

If this can be done, if a field is "required", but not displayed (hidden), will that not let the form submit?



i think so yes!

Cheers
Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
tidusx18 25 Feb, 2009
Hi Max,

Thanks for your quick response.

Umm..I hate to ask, but can you be a little bit more detailed. Like what is JS and maybe some details on the code like what it would look like, where it would go, etc. I tried searching in Google, but its no use if I don't know whats what : )

This form is essentially my whole site in a nutshell so without it I fail! 😟

Thanks again for your help with this.
tidusx18 25 Feb, 2009
lol, I just realized that JS means java scriptπŸ˜›
GreyHead 25 Feb, 2009
Hi Daniel,

Last question first. AFAIK the ChronoForms Validation code doesn't check hidden fields so 'required' and 'hidden' won't block submission.

Here's a simple example of the kind of code that you need. This happens to be using a pair of radio buttons - selecting from a drop-down is similar.
$doc =& JFactory::getDocument();
$script = "window.addEvent('domready', function() {
        $('cbt0').addEvent('click', function(event) {
		if ( $('cbt0').checked === true ) {
			$('no_cbt').setStyle('display', 'block');
		}
	});
	$('cbt1').addEvent('click', function(event) {
		if ( $('cbt1').checked === true ) {
			$('no_cbt').setStyle('display', 'none');
		}
	});
});
";
$doc->addScriptDeclaration( $script );
There are several things to notice about this[list]
  • It's MooTools code so the library needs to be loaded, Joomla 1.5 usually does this by default.
  • window.addEvent('domready', function() {loads the script after the window loads so the code can safely go in the page header (which the addScript Declaration does for you).
  • $('cbt0') identifies an item by id - so you need to make sure your tags have ids (you can also use names or classes but ids are usually simpler when you are dealing with specific fields).
  • addEvent('click', function(event) { adds an onClick handler to the tag - this replaces the need to ad onClick . . . to each tag individually and makes your code easier to maintain.
  • setStyle('display', 'block'); unhides (or hides with 'none') the identified tag so that you can switch blocks of code in and out of visibility.
  • Remember to handle the re-hide actions when the user changes selections.
  • [/list]
    Bob

    Later: added a missing "; :-(
    tidusx18 26 Feb, 2009
    Thanks Bob for your detailed response. I'll work on getting this to work and post my results.
    tidusx18 01 Mar, 2009
    Hi Bob,

    I've been trying, but I can't seem to get this to work. Would you be able to post an example like the last, but with a drop down box and text box? Like...if I select option 1 in the drop down, the text box is hidden, but if I select option 2, then the text box is displayed. From that I should be able to reproduce it to fit my need.

    Also, on a side question, can multiple forms be connected to (and be able to write to) a single database? At first, I had thought of making a form for each category I have on the site and making a menu with a link to each form.

    Sorry for all the bother.

    Daniel
    GreyHead 01 Mar, 2009
    Hi daniel,

    Here you go. The text box will only appear if you select Option 2
    <?php
    $script = "window.addEvent('domready', function() {
            $('select_0').addEvent('change', function(event) {
          if ( $('select_0')[2].selected === true ) {
             $('text_box_1').setStyle('display', 'block');
          }
       });
       $('select_0').addEvent('change', function(event) {
          if ( $('select_0')[2].selected !== true ) {
             $('text_box_1').setStyle('display', 'none');
          }
       });
    });
    ";
    $doc =& JFactory::getDocument();
    $doc->addScriptDeclaration( $script );
    ?>
    <div class="form_item">
      <div class="form_element cf_dropdown">
        <label class="cf_label">Select box</label>
        <select class="cf_inputbox" id="select_0" size="1" {cf_multiple} name="select_0">
        <option value="">Choose Option</option>
          <option value="option 1">option 1</option>
    <option value="option 2">option 2</option>
    <option value="option 3">option 3</option>
    
        </select>
        
      </div>
      <div class="clear">Β </div>
    </div>
    
    <div class="form_item" id='text_box_1' style='display:none;' >
      <div class="form_element cf_textbox">
        <label class="cf_label">Text box</label>
        <input class="cf_inputbox" maxlength="150" size="30" id="text_1" name="text_1" type="text" />
      
      </div>
      <div class="clear">Β </div>
    </div>
    
    <div class="form_item">
      <div class="form_element cf_button">
        <input value="Submit" type="submit" />
      </div>
      <div class="clear">Β </div>
    </div>
    

    Bob

    PS I also fixed a bug with my earlier post, sorry.
    tidusx18 01 Mar, 2009
    Thanks. I'll try it out and post results...

    Daniel
    tidusx18 22 Mar, 2009
    Hi,

    Just wanted to let you know that that code worked great and I was able to get the forms working the way I wanted. Thanks a lot.

    I was wondering though, I can make one of my forms the user registration form for Joomla right? You see, I'm having a problem because my site need to have different registration forms for different types of users (i.e. buyers, sellers). I was hoping that I could just create user groups and use a custom registration form with that code you provided for the user to first select their registration type. Then I guess figure out a way for them to automatically be added to the appropriate user group based on that. I think there's a component or something that can auto add users to a particular group during registration (if you know of any specific one, feel free to share lol).

    Let me know any suggestions or even if the above seems like a viable solution to you.

    Thanks! πŸ˜€

    Daniel
    GreyHead 22 Mar, 2009
    Hi Daniel,

    You could try using this code with the CF Joomla Registration PlugIn - it comes as standard with the recent versions. There's a tutorial in the DownLoads area.

    The Plugin will let you save extra information to a database table so you can identify your groups there. That's quite practical you just need user_id and group_id as columns in the table.

    Joomla's handling of groups is weak in 1.5, I think more is expected in 1.6. The phpgacl library has all the code to do complex permissions management but it isn't much used. There are various group management extensions but I don't have enough experience of any of them to comment.

    Bob
    tidusx18 22 Mar, 2009
    great. I'll give it a shot.
    tidusx18 22 Mar, 2009
    What if I want to have more fields that just the standard user name, password, etc? I'm referring to the part in the tutorial (page 14 in the PDF) where you insert the field ID's. Where would I put the field ID's for fields that are not listed? Or can I add to those somehow?

    Also, I'm assuming that since I'm using Community Builder, I should use the CB registration option. Right?

    Daniel
    GreyHead 23 Mar, 2009
    Hi Daniel,

    The CB Registration Plugin lets you store extra data in the CB Profile table - I think you may have to specify the fields there first (I'm not a CB user). That's seems to me the most practical place to save it.

    Bob
    tidusx18 23 Mar, 2009
    Yea. You were right.

    Thanks.
    laustin 23 Sep, 2009
    Hello,

    I've found a lot of code for this in other posts, but one thing is daunting me.

    I am having a problem with show/hide of multiple radio button options of the same id. I have a db of meals that are of three types: "Junior" "Mega" and "Fun" - they are kids meals. I have it so there are two radio button groups - one shows Junior, Mega, Fun - and the other shows the meal options/names. When the form is first loaded, the radio buttons are hidden on the second group until the first group choice is selected (style is set to none) - the text of the meal titles shows, but no buttons. Then I have Javascript running so that if Junior is selected in the first radio group, the meals where m_type is Junior show by finding all the radio options where id=m_type is set to Junior and switching their style to block and the rest to none.

    The problem is that I want all the radio options where id=Junior to be unhidden when Junior is selected in the first group, but only the first meal's button shows.

    Here is the code for the form HTML that is pertainent here:
    <div class="form_item">
      <div class="form_element cf_radiobutton">
        <label class="cf_label" style="width: 150px;">Meal Type</label>
        <div class="float_left">
          <input value="Junior" title="" class="radio" id="radio00" name="radio0" type="radio" />
          <label for="radio00" class="radio_label">Junior</label>
          <br />
          
    <input value="Mega" title="" class="radio" id="radio01" name="radio0" type="radio" />
          <label for="radio01" class="radio_label">Mega</label>
          <br />
          
    <input value="FUNtastic" title="" class="radio" id="radio02" name="radio0" type="radio" />
          <label for="radio02" class="radio_label">FUNtastic</label>
          <br />
    
        </div>
        
      </div>
      <div class="cfclear">Β </div>
    </div>
    
    <div class="form_item">
      <div class="form_element cf_radiobutton">
        <label class="cf_label" style="width: 150px;">Meal Options</label>
        <div class="float_left">
    
    <table>
    
    <?php
            $db =& JFactory::getDBO();
            $query ="SELECT * FROM `#__chronoforms_M_Add`";
            $db->setQuery($query);
            $results = $db->loadObjectList() ;
    
            foreach ($results as $result)  {
               echo ("<tr><td><input class='radio' id='".$result->m_type."' name='radio1' type='radio' style='display:none' /> <label for='".$result->m_type."' class='radio_label'>".$result->m_name."</label>");    }
    ?>
    
    
    </table>
        </div>
      </div>
    </div>
    


    And here is the Javascript:
    <?php
    $script = "window.addEvent('domready', function() {
            $('radio00').addEvent('click', function(event) {
          if ( $('radio00').checked === true ) {
             $('Junior').setStyle('display', 'block');
             $('Mega').setStyle('display', 'none');
             $('Fun').setStyle('display', 'none');
                   }
       });
       $('radio01').addEvent('click', function(event) {
          if ( $('radio01').checked === true ) {
             $('Junior').setStyle('display', 'none');
             $('Mega').setStyle('display', 'block');
             $('Fun').setStyle('display', 'none');
          }
       });
       $('radio02').addEvent('click', function(event) {
          if ( $('radio02').checked === true ) {
             $('Junior').setStyle('display', 'none');
             $('Mega').setStyle('display', 'none');
             $('Fun').setStyle('display', 'block');
          }
       });
    });
    ";
    $doc =& JFactory::getDocument();
    $doc->addScriptDeclaration( $script );
    ?>


    Also, there is one more problem I'm having that's of less importance - the radio button is showing above the label. I want it to show to the left as normal.

    Thank you for your help!
    GreyHead 23 Sep, 2009
    Hi Laustin,

    Id's are supposed to be unique in the page. If you use the same Id on several tags then the JavaScript/MooTools can't correctly distinguish them. I'm not sure how much of the problem this is but it's certainly a part of it.

    Try wrapping the second groups each in a div with its own id and control the display of the whole div.

    Bob
    laustin 25 Sep, 2009
    Thank you Bob! That makes sense, and your suggestion worked.
    kai920 18 Sep, 2010
    Hi Bob,

    I'm trying to adapt the code slightly to display a div on selection of one of two drop down values.

    Any idea why this isn't working?

    
    <?php
    $script = "window.addEvent('domready', function() {
            $('select_0').addEvent('change', function(event) {
          if ( ($('select_0')[2].selected === true) || ($('select_0')[1].selected === true) ) {
             $('isSchool').setStyle('display', 'block');
          }
       });
       $('select_0').addEvent('change', function(event) {
          if ( ($('select_0')[2].selected !== true) || ($('select_0')[1].selected !== true) ) {
             $('isSchool').setStyle('display', 'none');
          }
       });
    });
    ";
    $doc =& JFactory::getDocument();
    $doc->addScriptDeclaration( $script );
    ?>
    


    Thanks as always,
    GreyHead 18 Sep, 2010
    Hi kai920,

    Code seems fine with one exception - I think the logic of the second 'if' is wrong. Try
    if ( ($('select_0')[2].selected !== true) && ($('select_0')[1].selected !== true) ) {


    I tested this in the Form HTML box and it seems to work OK.

    Bob
    kai920 18 Sep, 2010
    Ah, you got it! Thanks πŸ™‚
    This topic is locked and no more replies can be posted.