Search code examples
javascriptsalesforceapex-codevisualforce

How to clear Lookup field value in Visualforce page?


Once a lookup field is populated and I open the same visualforce page later then the lookup field is prepopulated.

I want to put 'X' next to Lookup field so that when 'X' is clicked, the field value gets cleared.


Solution

  • You can do this with a simple bit of javascript which sets the value of the field to blank, there's just a bit of Force.com magic regarding obtaining the ID of the element to use. Below is a complete page which does what you need.

    <apex:page standardController="Contact">
        <apex:form >
            <apex:inputField id="accountLookup" value="{!Contact.AccountId}"/>
            <a href="#" onClick="document.getElementById('{!$Component.accountLookup}').value = ''; return false;">Clear</a>
            <apex:commandButton action="{!Save}" value="Save"/>
        </apex:form>
    </apex:page>
    

    Note that the recommended way of applying javascript to a link is to do it on page load, though you may find it simpler to do the above since it saves you having to drill down to the element {!$Component.Parent.Child.Grandchild} (which is needed when using <apex:pageBlock> etc.) and if javascript isn't enabled, your user will have bigger problems than your link not working!