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

Codeassembly

Try this.

jQuery(function($)
{
$('#first_select_with_default_value').change();
});

Posted on 2008-08-01 17:29:19
Bob

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).

How do I get that working? I'm using CodeIgniter, fwiw, so I'm using their validation lib to display form errors.

Cheers,
Bob

Posted on 2008-08-03 23:17:08
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-10 00: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 20: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 20:02:43
apadley

Sorry, I see that json_encode is PHP 5

Posted on 2008-02-25 19: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 20: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 20:02:43
abdullah

"json_encode" this below :

<?php

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

?>

Posted on 2008-03-21 20: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 19: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 19:46:36
Tekin

IE6 fixed but IE7 problem continue :(

Posted on 2008-04-09 15: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 21: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 21: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 21: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 21:22:23
mere56

No! Its not working in IE!

Posted on 2008-04-16 18: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 10: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 21: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 21: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-04 01: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 15: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-23 02:32:27
Bob

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

Posted on 2008-05-28 18: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 19:30:51
Jimmy

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

Posted on 2008-06-12 09: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 13: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-24 06:38:04
egemen

thanks antonio..

Posted on 2008-06-25 00:38:07
Neil Burton

Great script!

I'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!

Posted on 2008-08-01 16:33:09
Justin Kelly

Hi,

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

Posted on 2008-09-13 10:42:08
Justin Kelly

anyone know re above issues - chained select and iphone/opear mobile etc..

note: i'm will to put a $50 US bounty to get this issue fixed up it that helps

Cheers

Justin

Posted on 2008-10-02 00:54:09
Codeassembly

Justin, I don't think Opera mini supports ajax

"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.

Posted on 2008-10-03 12:58:29
Robson

I'm having a problem I couldnt solve using this (fantastic) plugin.
The 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.

Posted on 2008-10-08 11:14:43
Justin Kelly

Thanks!

i just rewrote this to be an onchange event and all is fine in opera-mini / iphone etc..

Cheers

Justin

Posted on 2008-10-13 02:33:41
Gijs

Hi, i have tried the example and looks great, but i think i am missing something.

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

Posted on 2008-10-26 18:47:27
Eric Renfro

Hello,

I 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.

Posted on 2008-12-05 11:53:14
hezll

Hello,I have found a bug with Drupal in IE
At 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

Posted on 2008-12-09 08:01:26
hezll

a question ,if I want transfer the first option val to the third

how?

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"

Posted on 2008-12-10 08:39:23
pr0t0

Hello,

Thanks for this usefull plugin.

I'm also interested in passing the 1st option to use it for the third box :)

Posted on 2008-12-17 16:56:28
evden eve nakliye

just rewrote this to be an onchange event and all is fine in opera-mini / iphone etc..

Posted on 2008-12-26 19:08:17
pozycjonowanie stron

Hi all! Just small update... for those who do not want to display empty options if option is null or 0 (zero).

Please 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!

Posted on 2009-01-02 22:06:22
WildMax

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.

[French] [No State] [No City]

Posted on 2009-01-20 13:39:11
Mahmoud M. Abdel-fattah

It works fine, but I want to use many of it on one page, in another way I want to use it with :

http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/


How can this be done ?

Posted on 2009-02-05 00:22:21
bharanikumar

The code not working for me,

It 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

Posted on 2009-02-13 18:22:25
hans

Posted on 2009-02-25 19:50:20
AD

Although I got your code working fine, here's what I'd to see a tutorial on.

A chained select using PHP/MySQL, with 3 tables lets say countries -> states -> cities

And using ajax with the fancy "loading" div..

Thanks

Posted on 2009-03-06 17:23:49
Jan

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 14:07:41
FSan

Can this work with any number of selects?
More than 3?
Is there any consideration to make it work with let's say 4?
Thanks a lot

Posted on 2009-03-21 18:30:38
Jan

FSan (and most others):
Use 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.

Posted on 2009-03-24 21:56:54
Edward

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 22:19:22
Videolu Dersler

Thanks!

i just rewrote this to be an onchange event and all is fine in opera-mini / iphone etc..

Cheers

Justin

Posted on 2009-04-21 14:55:28
lelebart

hi!
i 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.

Posted on 2009-04-26 21:51:09
Akis

Hello,

I'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

Posted on 2009-05-04 22:22:00
Alex

Hello,

can I make a link from the choice of the third select box?? Please help!!

Posted on 2009-05-08 16:17:28
Katrin Konstantin

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.

Thanks in advance

Posted on 2009-05-09 14:03:24
Michael

Hi,

I'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.

Posted on 2009-06-09 07:50:22
Roby

I am using the following library's

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

Posted on 2009-06-24 18:37:16
c.y

can you give an example when using the defaultValue?

Thanks.

Posted on 2009-07-20 08:29:44
Picas

I replace
$array[] = array('1' => 'Data 1');

with
$link = mysqli_connect ('localhost', 'root', 'picas', 'db_biodataalumni');
$queryjk =("select * from m_fakultas");
$resultjk = mysqli_query($link,$queryjk) or die (mysqli_error());

while($row=mysqli_fetch_array($resultjk)){
$array[] = array("$row[idfakultas]" => $row[fakultas]);
}

to be a dinamic combobox from db, but how to pass the value to next combobox..??

how to change $_GET['_value'] == 2 to idfakultas so the third combobox can load a data from database..

} elseif ($_GET['_name'] == 'state')
{
if ( $_GET['_value'] == 2 )//New York
...

I'm Confuse

Posted on 2009-07-29 09:09:32
Raymond

Great script! One question though, what code would I use to echo a URL under each drop down menu. So for instance, a user selects "USA" and under that drop down a text link appears? Thanks so much!

Posted on 2009-08-19 22:36:30
Spikezz

Here's a simple way to fix browser display problems with html entities. For example if you are indenting the combo box options with &nbsp; characters, we need to have the browser re-evaluate the html inside the options.

Change the jQuery.fn.chainSelect function in jquery.chainedSelects.js as follows:

var new_html = '';
for (i = 0; i < data.length; i++)//iterate over all options
{
for ( key in data[i] )//get key => value
{
//$(target).get(0).add(new Option(data[i][key],[key]), document.all ? i : null);
new_html += '<option value="' + key + '">'+data[i][key]+'</option>';
}
}
$(target).html(new_html);

Posted on 2009-09-15 23:39:17
Dragos

hello. i'm using this script i find useful, but i have two form in same page, with same class and i want both to change, i don't know javascript and jquery, but i think its useful someting like each function. Can you help me please?

Posted on 2009-11-06 20:45:07
Charles

Hello All,

Great plugin - I got it working in very short order. The only thing that hung me up was what to query in my PHP script that returned the JSON array. For those in the same boat: your script will work with two variables passed: "_name" - the ID (not class) of the field that was changed, and "_value" the value of the option that was selected. Since my PHP page will only serve requests for a specific field I did not use "_name".

Now I have a question. I am a newbie to jQuery and Javascript so pardon what may be a stupid question: how can I assign a class to the options returned from the JSON array?

Thanks,
Charles

Posted on 2010-01-07 18:05:55
Doli Anggia Harahap

Very great Plugin.
I have been used this for some of my tasks. But today i faced problem.
I need to do multiple select. Is it possible?

I have try to put something like this:

<td>
<div class="selHolder">
<h3>4. Dip (next...)</h3>
<select id="dipSelect" name="dip[]" size="5" multiple="multiple">
<option>[none selected]</option>
</select>
</div>
</td>

<td>
<div class="selHolder">
<h3>5. Fault</h3>
<select id="faultSelect" name="fault[]" size="5" multiple="multiple">
<option>[none selected]</option>
</select>
</div>
</td>

I put multiple in DIPSELECT. And in javascript:
$('#dipSelect').chainSelect('#faultSelect','modules/tab_content/index_controller.php',
{
usePost : true,
after:function (target)
{
$(target).css("display","inline");
}
});

I use POST to get array from the DIPSELECT.


and in serverside:
$dip = $_POST['_value'];


My Question, i don't get any ARRAY value for $dip even i select more than one in DIPSELECT. How can we do this multiple by using this plugin??

Thanks and very great works!!!

Posted on 2010-01-10 17:42:56
John

Thanks for this great script, but howto get this to work with content of a mysql database? all three dropdowns i mean.

Could someone please help me on this?

http://www.mijnbazaar.nl

Posted on 2010-01-11 16:20:20
Nix

Hi
I am not even a coder; I just started to learn.
Your online demo is exciting.
But downloaded files seems not working; some of the other guys also commented the same (Akis, bharanikumar), but no one replied a solution.
Is it like not for beginners...?
Thanks in advance

Posted on 2010-01-29 11:30:03
Geda

Hi,
No! Its not working in IE8

Posted on 2010-02-13 01:47:35
Sheldon

Fails in IE8

Posted on 2010-02-20 06:24:02
Kamil

@Nix: Just change the path (/examples/jquerycombo/combobox.php) in test.html lines 11 and 24 to correspond to your directory structure.

Posted on 2010-02-21 14:48:37
Amine

Very usefull tutorial ... I got it to work with mysql and everything. But I'm stuck now when I try to post the form :
I kept only two select boxes : country and state
I took off the code related to the 3rd select
the refresh works perfect with the two selects ... but after filling the rest of the form and submitting it ... I end up with the page combobox.php ... and error due to the fact there was no get value.


Notice: Undefined index: _name in D:\wamp\www\aminelab\combobox.php on line 8
[{"1":"Data 1"},{"2":"Data 2"},{"3":"Data 3"}]

Posted on 2010-03-28 23:56:15
Jorge Mario Valencia

first of all i wanna thank's for this great easy to use plugin, thank's a lot, want to comment too that i've made some changes to it in order to acomplish some requirements i need, let it get back to its deafault state when the user selects a default text i.e choose one country and a setting option that let set this default text, hope this interst you, and want to know how could i upload this version to let you check it out and decide if it could be use as a official version, thank's again.

Posted on 2010-04-13 17:11:14
Jorge Mario Valencia

first of all i wanna thank's for this great easy to use plugin, thank's a lot, want to comment too that i've made some changes to it in order to acomplish some requirements i need, let it get back to its deafault state when the user selects a default text i.e choose one country and a setting option that let set this default text, hope this interst you, and want to know how could i upload this version to let you check it out and decide if it could be use as a official version, thank's again.

Posted on 2010-04-13 17:45:56
Kamil

@Nix: Just change the path (/examples/jquerycombo/combobox.php) in test.html lines 11 and 24 to correspond to your directory structure.

Posted on 2010-02-21 16:41:42
Raymond

Great script! One question though, what code would I use to echo a URL under each drop down menu. So for instance, a user selects "USA" and under that drop down a text link appears? Thanks so much!

Posted on 2009-08-20 15:17:58
Stieven

Hi,

Now the second and third combobox are loaded hardcoded like this:
$array[] = array('1' => 'New York');
$array[] = array('2' => 'Montana');
$array[] = array('3' => 'Texas');

Now I need to load the second combobox, I only use two of them, with data from the database. When I put my db logic in there the loading box is displayed but nothing happens.

Can anyone help me? Below the code I use now in combobox.php:
?php
require_once(".\classes\db\db.class.php");

$array = array();
if ($_GET['_name'] == 'category')
{
if ( !empty($_GET['_value']))
{
$db = new DB(timetracker, localhost, timetracker, timetracker);
$result1= $db->query("SELECT id,description FROM subcategory", true);

while( $row=mysql_fetch_assoc($result1) )
{
$array[] = '$row['id']';
}
mysql_free_result( $result1 );

//$array[] = array('0' => 'dsfsdfsdfsdf');
}
else
{
$array[] = array('0' => 'No state');
}
}
echo json_encode( $array );
?>

Thx, it's the first time I try this :)
Grts,
Stieven

Posted on 2010-08-24 00:08:02
lanner

Hi

How to use this with a sql table ?

Thanks

Posted on 2010-09-14 17:31:50
pj

Hi,

could you please help me using this functions with variables instead of selectors' id?

i have diffrent amount of selects generating by a sciprt. their ids are:

country_1
country_2 etc.

when i'm trying to use it this way:
$("#country_"+ i +"").chainSelect("#city_"+ i "",'wybierzpole.php');

where var i is an incrementing index of select boxes.

doesn't work.
could you please help me to work it out?

Posted on 2010-09-18 16:33:20
OpenBSD

Hi, Your Plugin And code worked fine But i have 2 question!!
1- how to add option value (value="" or class or id etc) for send data form. ( state / city )?? Example : sign in form.
2- your php example code is 4 country and worked for 1 country!(usa / nweyork ... / ... ) can you tell me how to worked for other country. please php code .
Thanks.
Best regards.

Posted on 2010-12-13 20:22:27
Josef

Hi,

how can I print the arrays from a mysql database in this script?

Posted on 2011-01-14 10:27:57
komal

i want to redirect my page according to selection values of the combobox. that means that i hav dynamically binded combobox which has all the necessary site names. now i want that whenever i select particular site name, that particular site page should be displayed that means that my page should be redircted according to the selection values of the combobox.

Posted on 2011-11-07 07:17:34
Czeslav

Hello,

I'm trying to modify the script so i can generate any number of comboboxes, as data will be loaded from MySQL database.

Will something like this work??
jQuery.fn.chainSelect = function( target, url, settings )
{
return this.each( function()
{
$(this).change( function( )
{
settings = jQuery.extend(
{
after : function(){
$("#loading").css("display","block");
//$(target).css("display","inline");
addComboBox(target,target,"comboBoxSpan");
//recursive call
$("#"+target).chainSelect($_GET['_value'],url);
},
before : function(){
$("#loading").css("display","none");
},
[...]
Thx for help

Posted on 2011-11-25 14:58:58
Conrad

Hey man - this was just what i was looking for. If you can guide me on how to do one more tweak to it, it would be perfect.

How can I get two fields to not display (or display disabled) till the first choice activates the second choice. Likewise, second choice activates the final.

Posted on 2011-12-19 20:34:22
Conrad

Hey man - this was just what i was looking for. If you can guide me on how to do one more tweak to it, it would be perfect.

How can I get two fields to not display (or display disabled) till the first choice activates the second choice. Likewise, second choice activates the final.

Posted on 2011-12-19 19:24:27
Colin

With reference to the query about not showing later choices, I also had a need for those without choices in the second/third fields NOT to show

I amended the latter part of the combobox.php as follows

At the end of the creation of the array:

echo json_encode( $array );

} else

{
$array[] = array('0' => 'None');
}

In other words it only showed when there was a selection otherwise it remained invisible.

Posted on 2012-02-24 17:49:04
Colin

I wanted to be able to use the "state" data so I added to the html file - now php file

<?php
if ($_GET['_name']=="state")
{
echo $_GET['_value'];
}
?>

But I get an error message
Notice: Undefined index: _name in C:\web\jquerychained\test.php on line xxx

but the similar coding works fine in combobox.php

Where am I going wrong?

Posted on 2012-02-24 14:23:48
Hans

Hi there,

I am looking for a Multiple Category Selection plugin!

I have a website that I am just building for Tourism.

At the moment I am using the AVH Extended categories as a widget to allow my users to seach categories. You can see example here : http://puravidaguide.com/costa-rica/category/san-jose-province-costa-rica/restaurants-in-san-jose-province-costa-rica/

As I have numerous categories and have many more to add, user searching would be much easier if I had a multiple category seach option that autopulated the search fields below,

Such as: In this case, if I wanted to search for an Indian restaurant in San Jose CIty

1st Search Box

Province / State - in this case user chooses San Jose Province

2nd Search Box

City - in this example the user would be shown the cities in San Jose Province , and choose San Jose City

3rd Search Box

Activity (restaurants / hotels / sports etc) - in this example the user would choose 'Restaurant'

4th / final Search Box

Further define Activity ( price / food type etc) in this example a user would choose 'Indian'


I have tried the multi category selection feature, however it does not create multiple fields if the categories are not high level, so this does not work for me.

Any other suggestions of plugins that I could use? I am not experienced with Jquery. the site is usign wordpress and thesis 1.8

Thanks for any help,

Hans

Posted on 2012-03-11 23:32:15
NileshT

Nice Plugin!!!

But I have issue. if I m selecting first dropdown, second dropdown fills, after selecting or changing from second dropdown, third dropdown fills, now i want to fill forth dropdown on change of 3rd dropdown but it depends on all above dropdown. So my query is:

$query = "select col1,col2 from table1 where country = 'dropdown1_value' and state = 'dropdown2_value' and city = 'dropdown3_value'";

In my case, i m only getting dropdown3_value, so how i will get dropdown1_value, dropdown2_value and dropdown3_value?

Posted on 2012-03-22 11:09:38
Arnold

How about when first load of the page, the "France" chained values must be shown as well. Hope anyone can help me with this.

Posted on 2012-03-20 11:50:47
Ali

Hello

I tried your last comment using

jQuery(function($){$('#billing_country_id-5').change();});

To try to manually refresh the states list but that didn't work. Any other ideas?

Posted on 2012-04-03 12:32:00
huthief

To NileshT: Do you get the answer ? I have the same case.

Posted on 2012-06-20 16:06:37
pawan

When i put jquery, html code & php code in my page, its not working. Can u give suggestion?

Posted on 2012-05-29 15:11:56
Colin

I wanted to be able to use the "state" data so I added to the html file - now php file

<?php
if ($_GET['_name']=="state")
{
echo $_GET['_value'];
}
?>

But I get an error message
Notice: Undefined index: _name in C:\web\jquerychained\test.php on line xxx

but the similar coding works fine in combobox.php

Where am I going wrong?

Posted on 2012-02-24 13:25:57
umesh shejole

Very nice plugin shared but I am Looking for region country state city auto Select .

Posted on 2012-10-08 07:28:53
lee waddington

Hi

Great Script but have a slight problem, when i submit the form all values from both dropdown reset, is there a way to keep the values in the dropdown once it submitted to another page?

Posted on 2012-12-12 16:02:28
Dimpal

Hello,
I need server side source in C# and dynamically instead of PHP.
i have one table named Location in database and by using parentID i want to bind control Country,State,City dropdown.
can anyone help me?

table:location have following field
LocationID
ParentID
Type(type can b 1,2,3)
note: 1=country,2=state,3=city

i need this on clientside.

Posted on 2012-12-29 12:40:10
Mauro Litsure

Hi,

I would like a better explanation of how to send additional parameters using the below code.

Below is javascript code.

$('#Distrito').chainSelect('#PostoAdmin','chained/combobox.php',
{
usePost : true,

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");
},
parameters : {'_id' : $(this).attr('id'), '_name' : $(this).attr('name')}
});

Below is PHP code:

if (isset($_GET['_name']) == 'Distrito') // if Distrito dropdown is selected, then fetch all Postos related;
{
$provincia = $_POST['send_prov'];
$distrito = $_GET['_value'];

...

}

Question is how to receive parameters in PHP code.

Posted on 2013-05-06 15:01:05

Make yourself heard

Categories

Subscribe

All Posts

All Comments

© Copyright CodeAssembly

All code is licensed under LGPL, unless otherwise noted

littlebubu