Wednesday, October 21, 2009

Create Cascading Dropdown Lists By Using JQuery

When I was building the Travelbug widget for Stuff.co.nz, I have been using jQuery as the standard JavaScript library for most of  web projects for Stuff. Such as "Most Popular Box", "Pointers Slider" ...

Today, Let me guide you through on how to create cascading dropdown lists by using JQuery.

Here is a simple demo. Please look at the "Deal" section down the right hand side column.
.

1. Include jqury.js. You can get JQuery from here.
<script language=”javascript” src=”jquery.js”></script>

2. Write this simple function in a javascript block in head.
function makeSublist(parent,child,isSubselectOptional,childVal)
{
 $("body").append("<select style='display:none' id='" parent child "'></select>");
 $('#' parent child).html($("#" child " option"));
 
  var parentValue = $('#' parent).attr('value'); 
  $('#' child).html($("#" parent child " .sub_" parentValue).clone());
 
 childVal = (typeof childVal == "undefined")? "" : childVal ;
 $("#" child ' option[@value="'  childVal  '"]').attr('selected','selected');
 
 $('#' parent).change( 
  function()
  {
   var parentValue = $('#' parent).attr('value'); 
   $('#' child).html($("#" parent child " .sub_" parentValue).clone());
   if(isSubselectOptional) $('#' child).prepend("<option value='none'> -- Select District -- </option>");
   $('#' child).trigger("change");
                        $('#' child).focus();
  }
 );
}
This function takes 4 arguments: the parent select input’s id, the child select input’s id, and a boolean value to indicate whether to select an item from child list by default.

For example: makeSublist(’Regions’,'Districts’,false, 1);

This function will make the options of ‘Districts’ list depending on the selection of ‘Regions’. And user have to select
a location from ‘Districts’.
Here ‘Regions’ and ‘Districts’ are the IDs of parent and child select input respectively.

3. Add a class to the ‘<option>’s of the child list box. The class name will be the value of it’s parent ‘<option>’ in parent Districtsox with a ’sub_’ prefix.
Suppose, in parent Districtsox there is an item “Auckland”. Its value is ‘akl’:
<option value="akl">Auckland</option>
When the item "Auckland" will be selected, the sub-items should be visible in child Districtsox. These items should hold the class name ’sub_akl’:
<option class="sub_akl" value="Auckland City">Auckland City</option>
<option class="sub_akl" value="Rodney">Rodney</option>
<option class="sub_akl" value="North Shore">North Shore</option>


4. Now you are ready. On ‘$(document).ready’ event of Jquery, run the function to associate your list boxes.
$(document).ready(function()
{
makeSublist(’parentID’,'childID’, false, 1);
});

5. Testing out! and Questions??

12 comments:

January 26, 2013 at 11:37 PM Anonymous said...

Please let me know if you're looking for a writer for your weblog. You have some really good articles and I think I would be a good asset. If you ever want to take some of the load off, I'd absolutely love to write some articles for your blog in exchange for a link
back to mine. Please send me an e-mail if interested.

Thank you!
Also visit my site transfer news epl 2013

January 26, 2013 at 11:44 PM Anonymous said...

whoah this weblog is magnificent i like studying your articles.

Keep up the great work! You know, a lot of people are hunting round for this
info, you can help them greatly.
Feel free to surf my web site ; latest mufc transfer news man utd

March 20, 2013 at 1:00 AM Anonymous said...

Luckily, there are many methods in safely removing unwanted hair.
Right away register your GHD curly hair straightener concerning the GHD webpage so that you just can enact the
2-year ensure as well as to look at to make certainyours is genuine.
Its intention is to offer you ideal cosmetics which are safe and substantial in quality,
all the way through the world.

Feel free to surf to my web page hair products

April 9, 2013 at 12:56 AM Anonymous said...

Luckily, there are many methods in safely removing unwanted hair.
Likewise, using imported shampoos and conditioners from a tropical country when your climate is cold
and temperate is not such a good idea. The product should be one that is
made for your type of hair, whether it be dry, oily, curly or
straight.

Here is my website; hair products

April 11, 2013 at 4:20 AM Anonymous said...

Personal opinion is generally exhibited in various
types of editorial writings. This is a growing and profitable market with the increase in ability for all types of business- large
or small - to do business in an international platform and other
is National Newspaper Networks combine newspapers from several
States within the USA. They also tend to endear themselves to populations in
times of severe duress and hardship by well funded relief efforts and other charitable initiatives, which make them look incredibly social compared to corrupted governments.
Some say it would have, because there is an ongoing collaboration between
the two groups in attacks on Israel. I want them to be thrilled by
the idea that each of us is capable of running into high adventure
on every street corner and in every friendship.


my page - click here

April 16, 2013 at 7:29 AM Anonymous said...

There are a few types, mainly fine, regular, or rough.
It can also be left in the hair as a conditioner but it may be hard to explain the tomatoes.
Almost from the time of our grandparents and other
ancestors, the advantages of using olive oil are known to all.
The remaining oil in the scalp for a day and then follow up with
a shampoo the next morning. There are many products these days that can help
with keeping your hair in good condition but what of oils.


My page :: hair products

April 20, 2013 at 11:41 PM Anonymous said...

And a key to the programs success will be the development
and implementation of an outreach and education campaign to encourage participation in the CLASS program.

The Bluetooth Headset is a symbol of recognition and acceptance.

licitations with regards to making ones cachet that is most
certainly Talbots at present. The following year, at the age of thirty-eight, he matriculated
at the Louisville Dental College in Kentucky, where
he remained until he was graduated. The delivery of Linda Mc - Cartney
sausage rolls package is usually in frozen form.

Also visit my weblog Rhamphosuchus

June 6, 2013 at 6:10 AM Anonymous said...

This may amazement you, but it is a world and this close to this is the clients FICO top-superior.
You can utilise currency for many purposes such as complimentary food
market bills, home renovation, commendation bills, home renovation,
assets card dues, hymeneals expenses, medical emergencies, buckshee market bills and lots more.
The cash is made available to you accessible online.
paydayukYou can select any of the loaner as point without bounteous any cautionary.
This loan artefact is accessible only for
those candidates who do definite position and form with genuine info.

June 14, 2013 at 12:11 AM Anonymous said...

When you eventually picked up a approved, your authorized plane of
finance will in all likelihood repaid from next paycheque.
Is at that place such a artifact as SBA loaner has an financial support feeling for your specific SBA Loan postulation.
There are many of necessity that a individual to
help cash in hand in the compass of 100-1500. payday loansConfronting business occasion gets quite
a hard, if in individual you such as electrical energy
bills, learned profession bills, home renovation, car repairs, recognition
card dues, and wedding ceremony expenses etc. These are similar to
that of unlatched loans, which then lets without running any assets checking phenomenon.

June 12, 2014 at 1:02 PM Anonymous said...

I know this if off topic but I'm looking into starting my own weblog and was wondering what all is needed to get set up?
I'm assuming having a blog like yours would cost a pretty penny?
I'm not very internet savvy so I'm not 100% certain.
Any recommendations or advice would be greatly appreciated.
Kudos

Look at my page :: click the up coming website

May 2, 2022 at 9:45 PM nasmison said...

replica bags china ANPW replica wholesale handbags GKRZ replica wholesale handbags CGSU

August 28, 2022 at 11:47 PM phane said...

q1y62h7q75 a5u87j3q24 c9c77n6b80 p2e41t7i76 w4j03m9v59 h6w26l4u32

Post a Comment