Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show fields based upon select value

I have the following challange.

I have an entry form whereby persons can add a new entry and when approved they can also edit it. The challenge is to hide specific fields based upon a selection. When a user adds a new entry, they have to select a specific category. based upon that, some fields are hidden.

This is the code that I am using so far:

<select name="entry.parent" size="1" style="width: 360px;" id="SPCatChooserSl" class="required">
<option value="">Selecteer categorie</option>
<option  selected="selected" value="55">- Option 1</option>
<option value="59">- Option 2</option>

</select>

<div id="option1">
<p>Hier comes option 1</p>
</div>
<div id="option2">
<p>Here comes option 2</p>
</div>

<script>
jQuery(function() {
jQuery('#option1').hide();
jQuery('#option2').hide();
 });

jQuery(function() {
jQuery("#SPCatChooserSl").change(function() {
    if (this.value == '55') {
        jQuery('#option1').show();
    } else {
        jQuery('#option1').hide();
    }
    if (this.value == '59') {
        jQuery('#option2').show();
    } else {
        jQuery('#option2').hide();
    }
    });
     });
   </script>    

This works when a user still has to choose a category. It hides the fields based upon selection.

However when a user edits the entry, the category is already choosen and will likely not be changed. Because of that, the DIVS option1 and Option2 are hidden and since the user does not select a category, the divs will never be visible.

So the question is: How can I check for a specific value in the select list, show the correct fields without a useraction.

I hope that my question/challange is clear :)

Thanks in advance!!!!!!!

like image 362
user1737711 Avatar asked Nov 12 '22 19:11

user1737711


1 Answers

You can update the options when the document becomes ready:

jQuery(function() {
jQuery('#option1').hide();
jQuery('#option2').hide();
});

function updateOption() {
    jQuery('#option1').toggle(this.value == '55');
    jQuery('#option2').toggle(this.value == '59');
}

jQuery(document).ready(function() {
    jQuery("#SPCatChooserSl").each(updateOption);
    jQuery("#SPCatChooserSl").change(updateOption);
});

Fiddle: http://jsfiddle.net/Mwnjk/

like image 168
nneonneo Avatar answered Jan 04 '23 01:01

nneonneo