Quantcast
Channel: Jquery –⇝ ajaxray ⇝
Viewing all articles
Browse latest Browse all 17

jQuery controlled Dependent (or Cascading) Select List

$
0
0

When I was searching the web for a client side dependent list boxes, I got some scripts. But some of them were very much static (static select name, option name etc.), some were vary complex. Then I thought to make it myself.
I have been using jQuery as the standard JavaScript library for most of my web project for some days. Writing javascript coding in jQuery is fun. So here goes my contribution using it.

Here is a simple demo.

Let me guide you through it.

1. Include jqury.js.

<script language=”javascript” src=”jquery.js”></script>

You can get Jquery from here.

2. Write this simple function in a javascript block in head.

function makeSublist(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+” .sub_”+parentValue).clone());
if(isSubselectOptional) $(‘#’+child).prepend(“<option> — Select — </option>”);
}
);
}

This function takes 3 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.

Example: makeSublist(‘listA’,’listB’,false);

This function will make the options of ‘listB’ list depending on the selection of ‘listA’. And user have to select an item from ‘listB’.
Here ‘listA’ and ‘listB’ 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 listbox with a ‘sub_’ prefix.
Suppose, in parent listbox there is an item “Flower”. Its value is ‘fl':

<option value=’fl’>Flower</option>

When the item “Flower” will be selected, only 3 items should be visible in child listbox. These 3 items should hold the class name ‘sub_fl':

<option class=”sub_fl” value=”1″>Rose</option>
<option class=”sub_fl” value=”2″>Sunflower</option>
<option class=”sub_fl” value=”3″>Orchid</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);
});

5. Enjoy :)


Viewing all articles
Browse latest Browse all 17

Trending Articles