Simple jQuery Dependent Picklist

Friday, January 18, 2013 by Aslam - The Alexendra

Hi All,
Today I am going to show you how to make dependent picklist on visualforce page with some few lines of code. This is client side dependent list. So it has following benefits:

1) No Action Function or Ajax, means we dont need to call server side script to filter the list of records.
2) Its based on javascript so its fast
3) We can extend the level of dependency

The idea here to use jQuery and one small method to make the dependency. I have got this idea from here.
1) First make your parent select list as below

<select id="accountList" size="1"> <option value="">-Select-</option> <apex:repeat value="{!accounts}" var="acc"> <option value="{!acc.Id}">{!acc.Name}</option> </apex:repeat> </select>
2) Make your child select list. Make sure to give option a class name like this "child_{parent_record_value}".

<select id="contactList" size="1"> <apex:repeat value="{!contacts}" var="con"> <option class="child_{!con.accountid}" value="{!con.Id}">{!con.Name}</option> </apex:repeat> </select>
3) Put the below code in your head section

function prepareList(parent,child,isSubselectOptional){ $("body").append("<select style='display:none' id='"+parent+child+"'></select>"); $('#'+parent+child).html($("#"+child+" option")); $('#'+child).html("<option> — </option>"); $('#'+parent).change(function(){ var parentValue = $('#'+parent).attr('value'); $('#'+child).html($("#"+parent+child+" .child_"+parentValue).clone()); if(isSubselectOptional) $('#'+child).prepend("<option> — Select — </option>"); }); }
4) Call the below method on load of the page. Make sure to pass proper parent and child select list ids.
$(function() { prepareList('accountList','contactList', false); });

Thats it. Now you can see on the page the dependency is created automatically.

You can download the code from here

You can see the working demo here

Aslam Bari


Abdul Vahid said...

Very Nice!

Anonymous said...

Very useful information...

harold emmers said...

Definitely going to use this little gem.
Thanks for the info.

Anonymous said...

Its very nice utility sir...with quick responding.... Nagendra

lulur bali alus said...

salam kenal bos. lagi jalan jalan pagi nih

Prakash said...

Nice code ..I am facing a scenario where pick-list depends on pick-list where that again depends on radio button means three dependent components... any idea how to achieve this .

Renjith Jose said...

Is step2 & Step3 are same?

Wade Lovell said...

Code link yields a 404 Not Found Error. Please correct.

Post a Comment