19
Jul/09
3

Cascading Selects

The script creates dynamically a set of select elements: the range in each following is related to the selected option in the previous one.

In the script source, you have to configure the form ID as on you page (default “mainform”) and the complete set of the select options.

They are implemented as one-, two- and three-dimensional arrays.

The last JSON version of this script is very flexible, but in the config part you have to deal with a lot of brackets and commas – be careful :)

To add your own function to onClick event of the submit button, insert it at the marked place on the bottom on the script (marked as “/*here you can insert your own function*/”)

Example:



Download the source:


How can I generate the cascading arrays from a database?


MySQL/PHP example (not suitable for the JSON version of Cascading Selects)

There are 3 related MySQL tables with country, city and street data:






This PHP code will generate the output for cascading arrays:


mysql_connect(”127.0.0.1″,”root”,”");

mysql_select_db(”project1″);

$i=0;

echo “level0=new Array()\n”;

echo “level1=new Array()\n”;

echo “level2=new Array()\n”;



$q0=”select country_name, country_id from country”;

$result0=mysql_query($q0);

$i=0;

while ($rows0=mysql_fetch_array($result0)) {

$id0=$rows0["country_id"];

echo “level0[".$i."]=’”.$rows0["country_name"].”‘\n”;

$q1=”select city_name, city_id from city where country_id=”.$id0;

$result1=mysql_query($q1);

$j=0;

echo “level1[".$i."]=new Array()\n”;

echo “level2[".$i."]=new Array()\n”;

while ($rows1=mysql_fetch_array($result1)) {

$id1=$rows1["city_id"];

echo “level1[".$i."][".$j."]=’”.$rows1["city_name"].”‘\n”;

$q2=”select street_name, street_id from street where city_id=”.$id1;

$result2=mysql_query($q2);

$k=0;

echo “level2[".$i."][".$j."]=new Array()\n”;

while ($rows2=mysql_fetch_array($result2)) {

echo “level2[".$i."][".$j."][".$k."]=’”.$rows2["street_name"].”‘\n”;

$k++;

} ;$j++;

} ; $i++;

}

?>




Comments (3) Trackbacks (0)
  1. nepptunus
    06:24 on July 30th, 2009

    Hi!

    Very interesting script.
    By far, the most understandable i’ve just found and would try for sure.
    However, my javascript and html knowledge are very basic.

    Can you please tell me how to implement it in an html form page?

    Many thanks!!!

  2. admin
    15:12 on August 26th, 2009

    Hi nepptunus,
    the best way to do it would be to download the JSON version of the script and configure it in the part marked as ‘config’ in such a way as to nest levels of your data in the correct sequence, as in the example.

  3. phos
    17:03 on January 21st, 2010

    Dear Andrei Luca,
    your JSON-style script is just what I was looking for. I find it extremely helpful and it saved me a lot of time and trouble.
    Thanks a lot!
    phos

Leave a comment

No trackbacks yet.