Simple chained combobox plugin for jQuery

2008-02-03

Very simple chained selects plugin for jQuery with JSON processing and callback feature, chain multiple selects with ease.

Chained combobox live demo

Example

To chain combobox state to combobox country and combobox city to combobox state you must write the following code. The first parameter is the target combobox, the second the url and the third one is a callback function to run after the data is returned.

I first hide the country and city comboboxes and then show them using the callback function "function (target) { $(target).css("display","inline");}". The callback function gets the target combobox id as parameter.

$(function()
{
	$('#country').chainSelect('#state','/examples/jquerycombo/combobox.php',
	{ 
		before:function (target) //before request hide the target combobox and display the loading message
		{ 
			$("#loading").css("display","block");
			$(target).css("display","none");
		},
		after:function (target) //after request show the target combobox and hide the loading message
		{ 
			$("#loading").css("display","none");
			$(target).css("display","inline");
		}
	});
	$('#state').chainSelect('#city','/examples/jquerycombo/combobox.php',
	{ 
		before:function (target) 
		{ 
			$("#loading").css("display","block");
			$(target).css("display","none");
		},
		after:function (target) 
		{ 
			$("#loading").css("display","none");
			$(target).css("display","inline");
		}
	});
});

The html code

<form name="formname" method="post" action="">
	<!-- country combobox -->
	<select id="country" name="country">
	<option value="1" selected>France</option>
	<option value="2">Romania</option>
	<option value="3">Usa</option>
	<option value="4">Brazil</option>
	</select>
	<!-- state combobox is chained by country combobox-->
	<select name="state" id="state" style="display:none"></select>
	<!-- city combobox is chained by state combobox-->
	<select name="city" id="city" style="display:none"></select>
</form>

Server side script (php)

The server side script receives 3 parameters throught $_GET :$_GET['_id'],$_GET['_name'] and $_GET['_value']. (or $_POST)

$_GET['_id'] represents the id of the calling combobox, $_GET['_name'] the name of the calling combobox and $_GET['_value'] the value selected. The script must return a json array like in the example below.

<?php
$array = array();
if ($_GET['_name'] == 'country') 
{
	 if ( $_GET['_value'] == 3 )//usa
	 {
		$array[] = array('1' => 'Montana');
		$array[] = array('2' => 'New York');	
		$array[] = array('3' => 'Texas');	
	  } else
	  {
		$array[] = array('0' => 'No state');
	  }
} elseif ($_GET['_name'] == 'state') 
{
	 if ( $_GET['_value'] == 2 )//New York
	 {
		$array[] = array('1' => 'New York');
		$array[] = array('2' => 'Another city');	
	  } else
	  {
		$array[] = array('0' => 'No city');
	}
} else
{
	$array[] = array('1' => 'Data 1');
	$array[] = array('2' => 'Data 2');	
	$array[] = array('3' => 'Data 3');	
}
echo json_encode( $array );
?>

To get all code for this example, including the jQuery plugin click here

Update: Thanks to all of you who sent comments on this post and offered solutions for making this plugin work also on internet explorer, following your suggestions I fixed the plugin so it now works on Ie6 and 7.

Share this with the world

Related

Comments

josoroma

Hi!

Im a jquery newbie, but i test your plugin and is an easy and perfect piece of art. Great work!

I was wondering how can i add a spinner gif while the data is obtained for the new select?

Thanks in advance.

Posted on 2008-02-09 17:57:51
CodeAssembly

I'm glad you liked it. I updated the example, it now displays a "Loading ..." div while fetching data. You can replace the div with a spinner gif.

Posted on 2008-02-12 13:14:04
apadley

I've installed the plugin, but get the following error:

Call to undefined function: json_encode()

I'd like to get this working.

Posted on 2008-03-21 14:02:43
apadley

Sorry, I see that json_encode is PHP 5

Posted on 2008-02-25 12:04:44
Marçal

Hi,

congratulations for your script, is very usefull. But i didn't get it work under IExplorer, just in Firefox.

I'm trying to make it work under IE, if someone have already done it please let me know.

Thanks.

Posted on 2008-03-21 14:02:43
Marçal

Hi again,

I have changed the following plugin script line:


$(target).append(option);//insert the option into the select



with this other one

$(target).append('<OPTION VALUE='+key+'>'+data[i][key]+'</OPTION>');//insert the option into the select

and now the script works also in IE.

I hope this help somebody ;)



Posted on 2008-03-21 14:02:43
abdullah

"json_encode" this below :

<?php

function json_encode($dizi) {
$veri = '[' . implode(',', $dizi) . ']';
return $veri;
}

?>

Posted on 2008-03-21 14:02:43
glenn

Hi,

For those who have trouble getting this in IE6 to work:

replace:

//option = document.createElement("OPTION");//create a new option
//option.value = key;//set option value
//option.text = data[i][key];
//$(target).append(option); //insert the option into the select

With :
//insert the option into the select
$(target).append("<option value="+key+">"+data[i][key]+"</option>");

There is something up with passing the .text attribute to the way it's constructed here. for some reason it does't work in IE and I cant be bothered to find out how to access the dom there. I could tell in FF that it was working.

For any cache issues perhaps you could also change the parameter line to this one:

parameters = { '_id' : $(this).attr('id'), '_name' : $(this).attr('name'), '_value' : $(this).val() , 'rrand' : Math.random()
};

As such it will not cache the request as some IE's don't even listen to the ajax global options.

Hope this helps some people here.

Glenn

Posted on 2008-03-21 13:42:16
glenn

It seems my previous posting didn't correctly arrive:

This is the line you need to use to get results in IE:

<code>
$(target).append("<option value="+key+">"+data[i][key]+"</option>");
</code>
<br/>

Replace all in the inner for loop with this line.

Btw, I really like this implementation, the size of the plugin is also heaven and I'm a big fan of php/jquery combo. This was right up my alley and it's being used in a production site as wel speak.

Thanks codeassembly. If you need some help with finetuning this let me know.

Posted on 2008-03-21 13:46:36
Tekin

IE6 fixed but IE7 problem continue :(

Posted on 2008-04-09 08:52:47
Remy

When I try using this I get a page error: expected ";"

I know my JSON is well formed and have even tried to force a semi-colon in just to see and the results are the same. I also can't get the demo to work? I don't see a script error but the effect is the same, select an option and the other select boxes are made visible but with no members? I have tried IE7/Firefox.

Posted on 2008-05-01 14:22:23
Mariano

Doesn't work for me in IE 7. With
$(target).append(""+data[i][key]+""); and stuff I only get empty selects tags...

Posted on 2008-05-01 14:22:23
Remy

Ok, I have been following this and have had a couple of issues, I stripped down my production environment to the bare essentials and ran my scripts in FF and IE7. I had no problems with FF and Firebug helped immensely. IE would not play ball, even though I had tried glenn's code (which incidentally precludes FF).

I have been doing a bit of digging around and looked at other jQuery options for modifying the select list. The following line has been verified on IE7 and Firefox 2 and I have used it in place of Glenn's solution. I would be interested to hear how this works in IE6.

$(target).get(0).add(new Option(data[i][key],[key]),document.all ? 0 : null);

This was found via an article on Dr Dobb's Journal (http://www.ddj.com/java/201000935?pgno=4)

Kudos to the author!

Posted on 2008-05-01 14:21:24
Mariano

Remy: Works here in ie 7 (thanks!). In ie 6, almost: the first select triggers ok, but when you click the 2nd or 3rd select you get a "object does not accept this property or method" (translation from spanish, so may be innacurate. The error is referring to a jquery method, not this script.

Posted on 2008-05-01 14:22:23
mere56

No! Its not working in IE!

Posted on 2008-04-16 11:10:34
Mike

Thanks Remy. The following tweak of your code works for me in FF, IE7, IE6 & Saf3:

$(target).get(0).add(new Option(data[i][key],[key]), document.all ? i : null);

Posted on 2008-04-23 03:28:00
radek


Doesn't work for me in IE 7. With

$(target).get(0).add(new Option(data[i][key],[key]), document.all ? i : null);
i get
"object does not accept this property or method."
on line $('#country').chainSelect('#state','/examples/jquerycombo/combobox.php',

Posted on 2008-05-01 14:23:33
Radek

To make it work on IE:

jquery.chainedSelects.js >> Line 36:
36: parameters : { '_id' : $(this).attr('id'), '_name' : $(this).attr('name') },
37: } , settings);
Remove comma at the end:

parameters : { '_id' : $(this).attr('id'), '_name' : $(this).attr('name') }
37: } , settings);

Posted on 2008-05-01 14:21:24
Derrick

As soon as I try loop one of these:

$array[] = array('1' => 'New York');

with something like:

foreach($count=1; $count=3; $count++)
{
$array[] = array($count => '$count');
}

I get this firebug error:

<b>Parse error</b>: syntax error, unexpected ';' in <b>F:\server2\Apache Group\... line 49 in jquery.chainSelect.js

Posted on 2008-05-03 18:41:06
Solomon

Hi

I have a JSP page which has 6 combo boxes.When i select a value in the first combo the other 5 will filter with values which is done using AJAX. Now the problem is if the value i selected in the first combo has a size say 50 the screen looks very bad with scroll bars on both sides....All the combos size varies according to the value selected in first one....

Can anyone give an idea to have all the combo boxes sizes fixed irrespective of how the AJAX fires.

Posted on 2008-05-20 08:13:34
Bob

I'm reading a directory of .mp3 files to create my second select list, but when I run the script I get this:

Error: invalid label
Source File: http://[mydomain].com/jquery.chainedSelects.js
Line: 48, Column: 4
Source Code:
{"0":["No Track"],"1":{"1":"23-29 Tick Tock Blues.mp3"},"2" .....
-----^

I can't for the life of me figure out why json_encode($array) would place square brackets around the first item, and curly brackets around the rest. Thoughts?

Posted on 2008-05-22 19:32:27
Bob

Nevermind, figured out what was going on. It was the way I was building the array.

Posted on 2008-05-28 11:07:38
PK

Same error as Derrick described - unexpected ';' in line 49 in jquery.chainSelect.js

Array in PHP looks like

$array = array('1'=>'22','2'=>'222','3'=>'444','5'=>'666','7'=>'88888');

Posted on 2008-06-08 12:30:51
Jimmy

How would you load the 2 dropdown with data when page is loaded

Posted on 2008-06-12 02:17:06
Antonio

So.. if you want to get it working on FF,IE6 and IE7

jquery.chainedSelects.js >> Line 36:
36: parameters : { '_id' : $(this).attr('id'), '_name' : $(this).attr('name') },
37: } , settings);
Remove comma at the end:

IN THE END IT WILL LOOK LIKE:
parameters : { '_id' : $(this).attr('id'), '_name' : $(this).attr('name') }
37: } , settings);


AND CHANGE line 53 TO:

$(target).get(0).add(new Option(data[i][key],[key]), document.all ? i : null);

it works :)

Posted on 2008-06-17 06:24:15
Wesley

I am using the following library's

<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jquery.metadata.js"></script>
<script type="text/javascript" src="/js/jquery.validate.js"></script>
<script type="text/javascript" src="/js/jquery.chainSelects.js"></script>


The chainselects works fine on a page by itself, but when I combine with jquery and validate functionality it blows up &function undefined.

Posted on 2008-06-23 23:38:04
egemen

thanks antonio..

Posted on 2008-06-24 17:38:07

Make yourself heard

Categories

Subscribe

All Posts

Javascript posts

All Comments

This post comments

© Copyright CodeAssembly

All code is licensed under GPL, unless otherwise noted