[SalesForce] How to hide & show Lookup in Visualforce Page

I have two fields.

  1. Lookup
  2. Preferences

Based on my Preferences I want my lookup to be visible and hidden. I am using jquery
j$(".class-name").hide() to hide the lookup and j$(".class-name").show() to show back.

Here is the condition on when the lookup should be seen and when not.

  1. In Preferences when the user selects only "XYZ" I want lookup to be hidden.
  2. In Preferences, when the user selects anything other than XYZ then I want to show the lookup again.

The problem here is it hides properly but when I try to show it an extra input box is shown in front of the lookup which I believe is coming from my show method. I tried using reRender but failed.

New to Salesforce and Coding. Any help will be appreciated.

Best Answer

Here is a page that you should be able to add in your org to see some working code that does what I think you want:

<apex:page standardController="Contact">

<apex:form>
    <apex:inputField value="{!Contact.AccountId}" html-class="targetClass"/>
    <apex:inputField value="{!Contact.Level__c}" html-class="controlClass"/>
</apex:form>

<script src="https://code.jquery.com/jquery-1.11.1.min.js"/>
<script>
var j$ = jQuery.noConflict();
j$(document).ready(function() {
    j$('.controlClass').change(function () {
        var control = j$(this);
        var hide = control.val() == 'Secondary';
        var target = j$('.targetClass');
        if (hide) {
            target.hide();
        } else {
            target.show();
        }
    });
});
</script>

</apex:page>

The jQuery code waits until the page has loaded then attaches code that is run whenever the picklist changes. This code checks the current value of the picklist and shows or hides the other field accordingly.

Hopefully you can adapt this to your fields and class names etc.