[SalesForce] How to hide fields (input) by jQuery – Visualforce

I would like to show or hide fields depending on the value of another field. I was not able to find and implement the existing topics.

function selectService (){
   if($jquery('[id$=inField1]').val() == "value_1"){
       /* TODO Hide $id inField2*/
   }
}

<apex:form>
    <apex:pageBlockSection title="Informations">
       <apex:inputField value="{!Object__c.Field1__c}" onchange="selectService();" id="inField1"/>
       <apex:inputField value="{!Object__c.Field2__c}" id="inField2"/>
</apex:form>

When the #inFields1 value = value_1, I want Hide #inField2. What are the best solution ? It must use the attribute 'rendered' ? Thank's

Best Answer

You can use rendered attribute of the apex:inputField. So if the Object__c.Field1__c = value_1 it will be not shown at all:

<apex:actionFunction name="showHideField2" reRender="mySection"/>

<apex:form>
    <apex:pageBlockSection title="Informations" id="mySection">
       <apex:inputField value="{!Object__c.Field1__c}" onchange="showHideField2();" id="inField1"/>
       <apex:inputField value="{!Object__c.Field2__c}" id="inField2" rendered="{!Object__c.Field1__c != 'value_1'}"/>
</apex:form>

The apex:actionFunction works like a normal javascript function but can do reRender of the visualforce components.

Or you can use a jQuery solution for that as well. You will need to define an label for the outputField and hide that label together with a field:

function selectService (){
   if($jquery('[id$=inField1]').val() == "value_1"){
       $jquery('[id$=inField2]').hide();
       $jquery('[id$=inField2Label]').hide();
   }
   else{
       $jquery('[id$=inField2]').show();
       $jquery('[id$=inField2Label]').show();
   }
}

<apex:form>
    <apex:pageBlockSection title="Informations">
       <apex:inputField value="{!Object__c.Field1__c}" onchange="selectService();" id="inField1"/>     
       <apex:pageBlockSectionItem>
           <apex:outputLabel value="{!$ObjectType.Object__c.fields.Field2__c.label}" id="inField2Label"/>
           <apex:inputField value="{!Object__c.Field2__c}" id="inField2"/>
       <apex:pageBlockSectionItem>
</apex:form>