Very simple chained selects plugin for jQuery with JSON processing and callback feature, chain multiple selects with ease.
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");
}
});
});
<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>
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
Try this.
Posted on 2008-08-01 10:29:19jQuery(function($)
{
$('#first_select_with_default_value').change();
});
Running into another issue. I'm using this to pull states or provinces based on whether US or Canada is selected from the first dropdown. No problem, works as advertised. However, if the user submits the form and there are errors, when the page reloads, the states dropdown is not repopulated with the state they selected (assuming they selected one).
Posted on 2008-08-03 16:17:08How do I get that working? I'm using CodeIgniter, fwiw, so I'm using their validation lib to display form errors.
Cheers,
Bob
Hi!
Posted on 2008-02-09 17:57:51Im 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.
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:04I've installed the plugin, but get the following error:
Posted on 2008-03-21 14:02:43Call to undefined function: json_encode()
I'd like to get this working.
Sorry, I see that json_encode is PHP 5
Posted on 2008-02-25 12:04:44Hi,
Posted on 2008-03-21 14:02:43congratulations 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.
Hi again,
Posted on 2008-03-21 14:02:43I 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 ;)
"json_encode" this below :
Posted on 2008-03-21 14:02:43<?php
function json_encode($dizi) {
$veri = '[' . implode(',', $dizi) . ']';
return $veri;
}
?>
Hi,
Posted on 2008-03-21 13:42:16For 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
It seems my previous posting didn't correctly arrive:
Posted on 2008-03-21 13:46:36This 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.
IE6 fixed but IE7 problem continue :(
Posted on 2008-04-09 08:52:47When I try using this I get a page error: expected ";"
Posted on 2008-05-01 14:22:23I 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.
Doesn't work for me in IE 7. With
Posted on 2008-05-01 14:22:23$(target).append(""+data[i][key]+""); and stuff I only get empty selects tags...
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).
Posted on 2008-05-01 14:21:24I 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!
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:23No! Its not working in IE!
Posted on 2008-04-16 11:10:34Thanks Remy. The following tweak of your code works for me in FF, IE7, IE6 & Saf3:
Posted on 2008-04-23 03:28:00$(target).get(0).add(new Option(data[i][key],[key]), document.all ? i : null);
Posted on 2008-05-01 14:23:33Doesn'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',
To make it work on IE:
Posted on 2008-05-01 14:21:24jquery.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);
As soon as I try loop one of these:
Posted on 2008-05-03 18:41:06$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
Hi
Posted on 2008-05-20 08:13:34I 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.
I'm reading a directory of .mp3 files to create my second select list, but when I run the script I get this:
Posted on 2008-05-22 19:32:27Error: 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?
Nevermind, figured out what was going on. It was the way I was building the array.
Posted on 2008-05-28 11:07:38Same error as Derrick described - unexpected ';' in line 49 in jquery.chainSelect.js
Posted on 2008-06-08 12:30:51Array in PHP looks like
$array = array('1'=>'22','2'=>'222','3'=>'444','5'=>'666','7'=>'88888');
How would you load the 2 dropdown with data when page is loaded
Posted on 2008-06-12 02:17:06So.. if you want to get it working on FF,IE6 and IE7
Posted on 2008-06-17 06:24:15jquery.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 :)
I am using the following library's
Posted on 2008-06-23 23:38:04<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.
thanks antonio..
Posted on 2008-06-24 17:38:07Great script!
Posted on 2008-08-01 09:33:09I'm trying to set a default value so the second selection box appears at load rather than requiring user input, but it does not appear to work or I'm doing something wrong!
$('#skillid').chainSelect('#subskillid','ajax.url',
{
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");
},
defaultValue:14
});
My HTML snippet is as follows
<select id="skillid"" name="skillid">
<option value="13">Skill A</option>
<option value="14">Skill B</option>
</select>
<select id="subskillid"" name="subskillid">
</select>
Any help would be appreciated!
Hi,
Posted on 2008-09-13 03:42:08first - thanks for the great plugin!!
1 problem:
- alls working fine until i tested on mobile browser (opera mini and ie on htc touch)
- the mini browser have a custom select box thing (like the iphone) and once you select an item in your select it doesn't seem to register
you can test the demo page http://www.codeassembly.com/examples/jquerycombo/test.html in the online opera mini demo at http://www.operamini.com/demo/ to see what i mean
anyone know a solution to this??
any help would be greatly appreciated as i need to get my chained select working on these mobile browsers
Cheers
Justin
anyone know re above issues - chained select and iphone/opear mobile etc..
Posted on 2008-10-01 17:54:09note: i'm will to put a $50 US bounty to get this issue fixed up it that helps
Cheers
Justin
Justin, I don't think Opera mini supports ajax
Posted on 2008-10-03 05:58:29"Given handset limitations and Opera Mini's client-server architecture, "Ajax" applications cannot be expected to work as expected on Opera Mini."
You can read more here http://dev.opera.com/articles/view/javascript-support-in-opera-mini-4/
As an alternative you can submit form data on combobox onchange event and reload the entire page.
I'm having a problem I couldnt solve using this (fantastic) plugin.
Posted on 2008-10-08 04:14:43The first option of my combo is "All the cities" and the option value is "" I've made everything so that the script isnt activated when this option is selected but nothing has worked. May someone help??
Thanks in advance.
Thanks!
Posted on 2008-10-12 19:33:41i just rewrote this to be an onchange event and all is fine in opera-mini / iphone etc..
Cheers
Justin
Hi, i have tried the example and looks great, but i think i am missing something.
Posted on 2008-10-26 12:47:27After choosing the first selection, i get a nice second selection, but then something wierd is happening.
The third part of this combo, seems not to depend on my second choice?
The option values are always numbered from 0 to X, so my third choice does not depend on my second?
For example:
// 1 = Demi
if ( $_GET['_value'] == 1 )
{
$array[] = array('1' => 'Demi 1');
$array[] = array('2' => 'Demi 2');
$array[] = array('3' => 'Demi 3');
$array[] = array('4' => 'Loop 1');
$array[] = array('5' => 'Loop 2');
$array[] = array('6' => '1140 systeem');
}
else
{
$array[] = array('0' => '---');
}
// 2 = WFI
if($_GET['_value'] == 2 )
{
$array[] = array('1' => 'Distiller 1');
$array[] = array('2' => 'Distiller 2');
$array[] = array('3' => 'Distiller 3');
$array[] = array('4' => 'Loop 1');
$array[] = array('5' => 'Loop 2');
$array[] = array('6' => '1150 systeem');
$array[] = array('7' => '1153 systeem');
}
else
{
$array[] = array('0' => '---');
}
and some more examples.
So, when i choose the first or second option, i always get teh same third selection from:
elseif ($_GET['_name'] == 'subdeel')
{
if ( $_GET['_value'] ==1 )//New York
{
$array[] = array('1' => 'New York');
$array[] = array('2' => 'Another city');
}
else
{
$array[] = array('0' => '---');
}
The generated source code is:
<form name="formname" method="post" action="">
<!-- country combobox -->
<select id="installatie" name="installatie">
<option value="99" selected="selected">Rest</option>
<option value="1">Demi</option>
<option value="2">WFI</option>
<option value="3">Drinkwater</option>
<option value="4">HVAC</option>
<option value="5">Stoom</option>
<option value="6">CIP</option>
<option value="7">Gassen</option>
<option value="8">Heet water</option>
<option value="9">Koelkasten/Vriezers</option>
<option value="10">Afvalwater</option>
</select>
<!-- state combobox is chained by country combobox-->
<select name="subdeel" id="subdeel" style="display: inline;"><option value="0">---</option><option value="1">Distiller 1</option><option value="2">Distiller 2</option><option value="3">Distiller 3</option><option value="4">Loop 1</option><option value="5">Loop 2</option><option value="6">1150 systeem</option><option value="7">1153 systeem</option><option value="0">---</option><option value="0">---</option><option value="0">---</option><option value="0">---</option><option value="0">---</option><option value="0">---</option><option value="0">---</option><option value="0">---</option></select>
<!-- city combobox is chained by state combobox-->
<select name="subsubdeel" id="subsubdeel" style="display: inline;"><option value="1">New York</option><option value="2">Another city</option></select>
</form>
Please help?
Hello,
Posted on 2008-12-05 04:53:14I was curious, I'm trying to pass values to the chainSelect function to be passed as further parameters to the URI, so I could include things like other select option's values for hierarchical selective data. Beings that the call is formed off a php script, in this example, the possability of using it with database lookups, live, is also there.
Say for example, I have a selection A, it has values that relate to selection B, and finally selection C which is based on the values of selection A + B together.
How would you do something like this? If you would, and have ideas, please email me any ideas, as I am not too familiar with js itself, let alone JSON or AJAX or jQuery themselves, I've mostly been involved in PHP, Perl, etc.
Hello,I have found a bug with Drupal in IE
Posted on 2008-12-09 01:01:26At first ,it's really a good job.I have try it under IE and ff,it's great.
But when I try to move it into a Drupal module ,I found a little bug in IE.
sturcter:
class1
/
1996-class2
\
class3
1997
g1
/
1998-g2
\
g3
and when I select the first option eg:1998,the second option chaned to g1.
but afterwhile the first option change back to 1996
this bug is found in IE ,not FF.and with Drupal
solution:
jquery.ChainSelect.js line 65: add //
if (settings.defaultValue != null)
{
$(target).val(settings.defaultValue);//select default value
} else
{
//$("option:first", target).attr( "selected", "selected" );//select first option
}
Ok ,now there is no problem.haha
a question ,if I want transfer the first option val to the third
Posted on 2008-12-10 01:39:23how?
because after_table
1999 beijng 1
1999 beijng 2
2000 beijing 1
2000 beijing 3
and now just only pass the second option val beijing to the third
as you see ,the sql "select * from after_table where city = beijing"the result is confused .
it must be "select * from after_table where city= beijing and year = 1999"
Hello,
Posted on 2008-12-17 09:56:28Thanks for this usefull plugin.
I'm also interested in passing the 1st option to use it for the third box :)
just rewrote this to be an onchange event and all is fine in opera-mini / iphone etc..
Posted on 2008-12-26 12:08:17Hi all! Just small update... for those who do not want to display empty options if option is null or 0 (zero).
Posted on 2009-01-02 15:06:22Please update in HTML file 2 times:
(...)
before:function (target)
{
$("#loading").css("display","block");
$(target).css("display","none");
},
after:function (target)
{
$("#loading").css("display","none");
$(target).css("display","inline");
//hide empty select's if == null (you can use == 0 for article example)
if ($(target).val() == null)
{
$(target).css("display","none");
}
}
(...)
Enjoy!
If there a way to onload the chained combobox, will get all the 3 textbox. Instead we had to select other option and back to first option.
Posted on 2009-01-20 06:39:11[French] [No State] [No City]
It works fine, but I want to use many of it on one page, in another way I want to use it with :
Posted on 2009-02-04 17:22:21http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/
How can this be done ?
The code not working for me,
Posted on 2009-02-13 11:22:25It just showing the loading image,
even i change the code like
$('#country').chainSelect('#state','/examples/jquerycombo/combobox.php',
To
$('#country').chainSelect('#state','combobox.php',
Even not working
Thanks
reach me at
bharanikumariyerphp at gmail dot com
If I use Korean or japan or china language.
Posted on 2009-02-25 12:50:20looks like this..
-------------------------
$array[] = array('1' => '´º¿å');
-------------------------
I can not see the language.
I see just blank..
What should I do..?
Although I got your code working fine, here's what I'd to see a tutorial on.
Posted on 2009-03-06 10:23:49A chained select using PHP/MySQL, with 3 tables lets say countries -> states -> cities
And using ajax with the fancy "loading" div..
Thanks
This is a ridiculous jquery-plugin. Using ajax for this purpose is silly unless the amount of data is large, and in that case another presentational approach with less clicks would be preferred. This should at a minimum be solved without any serverside integration, and with cached data created at point of data modification. The complexness in this project is totally useless, and only creates trouble. Added to my extensive list of useless, bad written jquery-plugins.
Posted on 2009-03-21 08:07:41Can this work with any number of selects?
Posted on 2009-03-21 12:30:38More than 3?
Is there any consideration to make it work with let's say 4?
Thanks a lot
FSan (and most others):
Posted on 2009-03-24 15:56:54Use this :
http://blog.kotowicz.net/2009/03/jquery-optiontree-demo.html
Chain boxes as many times you like. No Ajax, you prepare the date beforehand.
Although 4 clicks for the user to get to what he/she needs? Consider a nested pulldown menu.
I am trying to get the code to work. The first combobox shows and is filled. after select on first combobox the second and third boxes show, but are empty. What could cause this. Please advise.
Posted on 2009-04-14 15:19:22Thanks!
Posted on 2009-04-21 07:55:28i just rewrote this to be an onchange event and all is fine in opera-mini / iphone etc..
Cheers
Justin
hi!
Posted on 2009-04-26 14:51:09i gone mad with html special char, so i've added few lines to PHP the code, just before to json_encode:
[previous code]
//html special char fix by lelebart \\start
foreach($array as $key => $val) {
foreach($array[$key] as $chiave => $valore) {
$array[$key][$chiave] = utf8_encode($valore);
}
}
//html special char fix by lelebart \\end
echo json_encode($array);
hope to be useful. feel free to update.
Hello,
Posted on 2009-05-04 15:22:00I've downloaded and tested it but cannot make it work. When a make a choice from the first combo it displays "loading" and it doesn't display anything. I've changed the url of the combobox.php but still nothing. Anybody can help???????????
Thanks
Hello,
Posted on 2009-05-08 09:17:28can I make a link from the choice of the third select box?? Please help!!
I would like to know if there is a way to call a url when I choose something in the third combobox. For example when I choose a city eg. New York I would like automatically to be redirected to another webpage eg. newyork.html. I imagine that the links will be defined within the array. I don't know much about php so I need some help.
Posted on 2009-05-09 07:03:24Thanks in advance
Hi,
Posted on 2009-06-09 00:50:22I'm working on a PHP/MySQL version and so far so good.
Is there anyway to store a <option value="--id of selected country dropdown--">none</option> at the head of the STATE dropdown, once a country has been selected ?
Thanks for any tips.
I am using the following library's
Posted on 2009-06-24 11:37:16<script type="text/javascript" src="/js/jquery.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.
Make yourself heard