Recently I had the requirement of showing or hiding both the label and input item, depending on the selection within a select list.
So with this example, let's say my requirement is to hide the "Other Description" label and input item if "My select list" equals "- Select me -"
Otherwise, display the items and as an added bonus - set the label to the value of the selected list item.
First I need to modify the label so I have the ability to reference it in my JavaScript. So I edit my P1_OTHER_DESCRIPTION field and extend the HTML Table Cell Attributes in the Label section (not the Element section).
id="label_other"
Now I can define a script to do my work. It's highly likely this script will be used solely on this page so there's no real harm in adding it directly to the page attributes - unless you have a dedicated JavaScript file you add your scripting code.
So this would be added to the page footer text:
<script language="JavaScript" type="text/javascript"> <!-- function toggleOtherDesc(){ $f_Hide_On_Value_Item('P1_MY_SELECTLIST',['P1_OTHER_DESCRIPTION','LABEL_OTHER'],'hide_desc'); //I could also change my actual label, for instance to the value of my select list input item document.getElementById('LABEL_OTHER').innerText = $v('P1_MY_SELECTLIST'); } toggleOtherDesc(); //--> </script>Some points to note here
- $f_Hide_On_Value_Item is a pre-defined function you can call to hide a list of items based on the value of another. Its behaviour is documented online here. In this case I listed both the label I created an id for plus, the item name - surrounded by square brackets as to define an array.
- 'hide_desc' is the value I've set in this case when the input description is '- Select me'
- .innerText allows me to set the descriptive label, as long as I supply the id I defined for the label, not the item name you see in the Apex builder.
- $v will return the value in the field, as it would be posted. This is also documented in the JavaScript API reference page.
- The highlighted line 9 means the function will be called when you open the page, in this case after it's rendered. That way the fields will be shown/hidden depending on the set value in the select list.
Lastly, I can modify the P1_MY_SELECTLIST item to call the JavaScript each time the selection changes.
So I add
onChange="javascript:toggleOtherDesc();"
to the HTML Form Element Attributes in the Element section.So the final product will change the label to the selected value in the select list, or hide the label and input field if '- Select me -' is chosen.
There you have it!