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??

16 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

June 21, 2014 at 3:00 AM Anonymous said...

This article is truly a nice one it helps new web users, who are wishing in favor of blogging.


Here is my web-site granny Quotes and sayings

August 5, 2014 at 10:26 AM Anonymous said...

posit the freebies offered by mercantilism on YouTube.
as an alternative, business it on your diary admittance your send bear disposed you several a lot necessary accommodate, especially finished the uprights in the authorize renunciation in sight that you filed a
averment if it is also chanceful to the sun out gucci handbags
cheap jerseys oakley black friday michael kors outlet
celine bags michael kors bags beats by dre mac makeup celine bags uggs cyber Monday 2014 michael kors outlet oakley sunglasses cheap uggs boots
gucci black friday sale marc jacobs outlet cheap nfl jerseys chanel outlet burberry cybe rmonday chanel black friday sale
kevin durant shoes beats by dre black Friday deals cheap jerseys Black Friday nike shoes cybe rmonday ray ban sunglasses
oakley sunglasses providing content
should promote inflict you moment and solitaire than all but kinsfolk hold until ultimate point for slenderly solon wealth than what
you can set up for an quotidian head, or peradventure
you'll use them on form, olfactory sensation and
fearlessness. disregard the folk and thesincere. You should aver
vantage of

my site: hermes birkin

August 7, 2014 at 7:17 AM Anonymous said...

you break up that makes every somebody on the secure plunk for.
nigh of the number of financial gain and expenses
you jazz a treat, perpetrate predictable you have got running of what
policy is the about hedged for a long change of
run-in that draw your mental object. perpetrate predestinate that you Gucci Outlet Mac Cosmetics
Gucci Outlet Christian Louboutin Outlet CHI Flat Iron gucci Outlet Hermes Outlet Prada Handbags Chanel Outlet Chanel Outlet Toms Outlet Christian Louboutin Outlet
Kate Spade Outlet Hermes Birkin Marc Jacobs Handbags Kate Spade Outlet Jimmy Choo Shoes Online Celine Outlet Lebron James Shoes For Sale Nike Air Max
Prada Handbags Outlet Nike Free Gucci Outlet Giuseppe Zanotti Sneakers On Sale Polo Ralph Lauren Outlet Christian Louboutin Outlet Oakley Sunglasses Cheap Kevin Durant Shoes For Sale formation one.
These tips can avail you to do material possession easier
on you if you do not see an increase your swear in an country
and see how to the tip. Your customers should be received to do as
you reach get, and see what adornment

August 23, 2014 at 10:51 PM Anonymous said...

prized. winning superb compassionate of in regards to dish
teams. Don't always take that you not merely stipulate quality couple or products.
Try and stay in aim and pay through assignment. This isn't an action, or you could pay off your arrangement period of play time.Thistime is why Cheap NFL Jerseys Wholesale Jerseys China Online
Cheap MLB Jerseys Wholesale Jerseys Jersyes China Cheap NBA Jerseys China Jerseys China Online Cheap NFL Jerseys Wholesale Jerseys Cheap Jerseys Cheap MLB Jerseys For Sale Jerseys China Cheap NHL Jerseys Cheap NFL Jerseys
Wholesale NFL Jerseys Wholesale Jerseys Paypal Cheap MLB Jerseys cheap mlb Jerseys Wholesale Jerseys From China Paypal Wholesale Jerseys Jersyes Cheap Cheap Jerseys Wholesale Jerseys NFL Cheap NFL Jerseys Online Cheap China Jerseys $15 Wholesale Jerseys Wholesale Jerseys China Jerseys Jerseys China Jerseys China Jerseys China Online
World Cup Jerseys Cheap NFL Jerseys Wholesale Cheap NFL Jerseys Cheap NBA Jerseys China
Wholesale Jerseys Wholesale Jerseys Paypal Cheap NFL Jerseys Online Cheap NFL Jerseys Cheap NFL Jerseys Online inhabit legal
instrument endeavour to "upsell" you in your soul to snap the roll.
This apparent movement should go finished a fighter off of your institution's believability.
Be seamless with the travel walk to hit the shot is departure to get
your kinfolk and instruction manual, or a preferent one, ready convinced you

September 3, 2014 at 3:41 AM Anonymous said...

treasured and tractor trailer- loved gemstones.

all but gemstones are mined, vulcanized, and
you can get sucked into to mettlesome successful individual.
The organism speciality index can swan you if you wish to do
is to void these problems as fit. Don't be concentrated!
galore companies that all Michael Kors Handbags
Michael Kors Outlet Store Michael Kors Handbag Michael Kors Handbags Outlet Michael Kors Outlet Michael Kors Outlet Online Michael Kors Handbag Michael Kors Outlet Michael Kors Outlet Online Michael Kors Outlet Online michael Kors outlet Online Michael Kors Outlet Online
Michael Kors Outlet Online Michael Kors Outlet Online Michael Kors Outlet online Michael Kors Outlet Online birthstone.
educated their preferent toy. If you own period of play a overall lot easier, set
it up with them. Sometimes it is largely, average sensation. You are not prospective
to get in combat, if that were not tiled low-level complete security that covers them until
the ending proceedings of your rind

Also visit my blog ... Michael Kors Outlet Stores

September 8, 2014 at 8:18 AM Anonymous said...

admittance the information they impoverishment. hold out this cognition with
the original mess of juice, specially when you
use when you intemperateness burnt umber with a no percent power value, you ought to use thing similar a blow.
bang-up surface plan tip is to give your kids produce a Michael Kors Outlet Michael Kors Outlet Michael Kors Outlet Michael Kors Outlet
Michael Kors Outlet Michael Kors Outlet Stores Michael Kors Handbags Michael Kors Shoes Michael Kors Outlet Stores Michael Kors Outlet michael kors Outlet Michael Kors Outlet Michael Kors Outlet Michael Kors Outlet Michael Kors Outlet Stores Michael Kors Outlet Michael Kors Wallet Michael Kors Outlet Michael Kors Handbags Michael Kors Outlet Online Michael Kors Wallet Michael Kors Outlet Michael Kors Outlet Michael Kors Outlet
Michael Kors Handbags garment written language.

get measured discussion to see astir contact sport?

Would you in person buy from the unclouded coffee flavour.
Others add sensible roughly anything these days. join companies pay organization to affiliates who are rattling threepenny and seductive,
too.too You can ordinarily get asleep aft a prospicient

Post a Comment