Solved

How do I get these select boxes to cascade three times?

Posted on 2009-04-02
21
1,339 Views
Last Modified: 2012-05-06
I want to have a set of three cascading drop down boxes.
1) Select State/Province
2) Select City/Town
3) Select Area/Suburb

I have successfully managed to get the cities to cascade depending on the selection of the state/province... However, I want to cascade the areas/suburbs when the (dynamically created) city box is changed (onchange).

Also.. how do I obtain the value of each of the select boxes once the user has selected all three?  I want to use all three values.

Thanks in advance!

Nick
0
Comment
Question by:Chimeraza
  • 14
  • 7
21 Comments
 
LVL 6

Expert Comment

by:twocandles
ID: 24049687
For the first question, could you place some code? the same code you used for the first combo should work for the second.

The way to retrieve the value of a select is like this:

<select name="myselect">
<option value="1">option1</option>
 <option value="2">option2</option>
 </select>

if the option2 is selected you would receive in your processing page a parameter with name "myselect" and value "2". If you're using php, then you would access this value like this:

$_REQUEST["myselect"]


0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24050384
Sorry, thats the second time its done that... not attaching my code snippet...
************************************************************************

PHP file where the three select boxes will be... ************************************************************************
 

<script language="JavaScript" type="text/javascript" src="scripts/ajax_cascade.js"></script>

<select onchange="ajaxGET(this.value, 'casc_cities.php')">

				<?php $prov_set_res = get_stprov();

				while ($prov_set = mysql_fetch_array($prov_set_res)) {

				 echo "<option value='".$prov_set['SP_ID']."'";

				 if($cus_set['CUS_STATEPROV'] == $prov_set['SP_ID']) {echo " CHECKED";}

				 echo ">".$prov_set['SP_NAME']."</option>";

				}

				?>

</select>
 
 

************************************************************************

PHP file - casc_city_areas.php

************************************************************************
 

<?php 

	if (intval($_GET['ct_id']) == 0) {

			//redirect_to("index.php");

	}

	$ct_id = mysql_prep($_GET['ct_id']);

	echo "{".$ct_id . ": [''"; 	

	$ca_set_res = get_cityarea($ct_id);

	while ($ca_set = mysql_fetch_array($ca_set_res)) {

		echo ", '".$ca_set['CA_NAME']."'";

	}

	echo "]}";
 

?>
 

************************************************************************

PHP file - casc_cities.php

************************************************************************

<?php 

	if (intval($_GET['sp_id']) == 0) {

			//redirect_to("index.php");

	}

	$sp_id = mysql_prep($_GET['sp_id']);

	echo "{".$sp_id . ": [''"; 	

	$ct_set_res = get_citytown($sp_id, '');

	while ($ct_set = mysql_fetch_array($ct_set_res)) {

		echo ", '".$ct_set['CT_NAME']."'";

	}

	echo "]}";
 

?>
 

************************************************************************

Javascript file ajax_cascade.js

************************************************************************
 
 

    var xmlhttp = false;

        var reqObj = 

        [

                function() {return new XMLHttpRequest();},

                function() {return new ActiveXObject("Msxml2.XMLHTTP");},

                function() {return new ActiveXObject("Microsoft.XMLHTTP");},

                function() {return window.createRequest();}

        ];

        for(var i = 0, e = reqObj.length; i < e; i++)

        {

                try

                {

                        xmlhttp = reqObj[i]();

                        break;

                }

                catch(err)

                {

                        xmlhttp = false;

                }

        }

    function ajaxGET(data, page) {

        xmlhttp.open('GET', page + '?set=1&sp_id=' + data + '&cache=' + Math.random(), true);

        xmlhttp.onreadystatechange = function() {

            if(xmlhttp.readyState !== 4) {

                return;

            }

            else {

                if(xmlhttp.status === 200) {

                    var JSONData = eval('(' + xmlhttp.responseText + ')');

                    var placeholder = document.getElementById('placeholder');

                    while(placeholder.firstChild) {

                        placeholder.removeChild(placeholder.firstChild);

                    }

                    var select = document.createElement('select');

                    for(var i = 0, e = JSONData[data].length; i < e; ++i) {

                        select.options[i] = new Option(JSONData[data][i], JSONData[data][i]);

                    }

                    placeholder.appendChild(select);

                }

                else {

                    //something baaaad happened

                }

               

            }

            

        }

        xmlhttp.send(null);

    }

Open in new window

0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24050398
and also...$_REQUEST["myselect"] doesn't seem to work if the select box is created dynamically with AJAX... I may be wrong.
0
 
LVL 6

Expert Comment

by:twocandles
ID: 24050753
could you post the html, please?
0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24051540
this is the html..

<select onchange="ajaxGET(this.value, 'casc_cities.php')">
                                <?php $prov_set_res = get_stprov();
                                while ($prov_set = mysql_fetch_array($prov_set_res)) {
                                 echo "<option value='".$prov_set['SP_ID']."'";
                                 if($cus_set['CUS_STATEPROV'] == $prov_set['SP_ID']) {echo " CHECKED";}
                                 echo ">".$prov_set['SP_NAME']."</option>";
                                }
                                ?>
</select>
0
 
LVL 6

Expert Comment

by:twocandles
ID: 24052047
well, I was talking about the rest of the page. You're only showing one of the selects...
Do you disable the select once a value is selected?
0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24054483
Thanks for the response...  Basically the rest of the select boxes are created dynamically through javascript/ajax.  

Below the select box is:

<div id='placeholder'></div>

The javascript looks for id placeholder and inserts the select box...  I have it successfully inserting the city select box into the div...but I want the dynamically created select box (city) to create another select box when a value (city) is chosen...

Does that clear things up?
0
 
LVL 6

Expert Comment

by:twocandles
ID: 24057166
Ok, I see.

Then you may consider using a static select into a hidden div. Then make dynamic only the contents of the select, and the onchange event make the div visible again.

Also consider using a javascript library like jQuery (http://jqueryui.com/). It really saves you from writing lot of code when working with AJAX and Dynamic HTML.

If you consider this option, I can attach you some code I had to implement recently.
0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24057789
thanks...great ideas!!  Will let you know how it goes!
0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24058513
Been struggling with it for a while now...  I'm def open to using jquery...can you give me an example of using three cascading select boxes that draw their values from mysql with php....obviously you don't need to include actual queries or anything.

I started with jquery...except I don't know how to put the mysql data in the select box...

Have attached where I am at..

Thanks for all this help!!
<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE html

	PUBLIC "-//W3C//DTD XHTML 1.1 Strict//EN"

	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"

	  xml:lang="en"

	  lang="en">

	<head>
 

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

        <script type="text/javascript" src="jquery.cascade.js"></script>            

        <script type="text/javascript" src="jquery.cascade.ext.js"></script> 

        <script type="text/javascript" src="jquery.templating.js"></script> 
 

		

		<style type="text/css">

			.cascade-loading  	

			{																		

				background: transparent url("indicator.gif") no-repeat center; 					

			}

		</style>

	</head>

	<body>
 
 

	<h2>Chained</h2>

	<div>

		<label>Parent

			<select id="chained">

				<option value="A">A</option>

				<option value="B">B</option>

				<option value="C">C</option>

				<option value="D">D</option>

			</select>

		</label>

		<label>Child

			<select id="chained_child">

			</select>

		</label>

		<label>SubChild

			<select id="chained_sub_child">

			</select>

		</label>

	</div>

	<script type="text/javascript">

		jQuery(document).ready(function()

		{	

			jQuery("#chained_child").cascade("#chained",{					

				ajax: {url: 'data.js' },				

				template: commonTemplate,

				match: commonMatch 

			});

			jQuery("#chained_sub_child").cascade("#chained_child",{					

				list: list2,

				template: commonTemplate,

				match: commonMatch 

			});

		});

	</script>

	

	

    </h2></body>

</html>

Open in new window

0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 3

Author Comment

by:Chimeraza
ID: 24058520
Sorry this script is also in the head...  I want to change it from receiving data through these 'lists' and rather through a query
<script type="text/javascript">

			var list1 = [

				{'When':'A','Value':'A1','Text':'A1'},

				{'When':'A','Value':'A2','Text':'A2'},

				{'When':'A','Value':'A3','Text':'A3'},

				{'When':'A','Value':'A4','Text':'A4'},

				{'When':'B','Value':'B1','Text':'B1'},

				{'When':'B','Value':'B2','Text':'B2'},

				{'When':'B','Value':'B3','Text':'B3'},

				{'When':'B','Value':'B4','Text':'B4'},

				{'When':'C','Value':'C1','Text':'C1'},

				{'When':'C','Value':'C2','Text':'C2'},

				{'When':'D','Value':'D1','Text':'D1'},

				{'When':'D','Value':'D2','Text':'D2'}

				];

			var list2 = [

				{'When':'A1','Value':'W','Text':'SubchildA1a'},

				{'When':'A1','Value':'X','Text':'SubchildA1b'},

				{'When':'A2','Value':'Y','Text':'SubchildA2a'},

				{'When':'A2','Value':'Z','Text':'SubchildA2b'},

				{'When':'B1','Value':'W','Text':'SubchildB1a'},

				{'When':'B1','Value':'X','Text':'SubchildB1b'},

				{'When':'B2','Value':'Y','Text':'SubchildB2a'},

				{'When':'B2','Value':'Z','Text':'SubchildB2b'},

				{'When':'C1','Value':'W','Text':'SubchildC1a'},

				{'When':'C1','Value':'X','Text':'SubchildC1b'},

				{'When':'C2','Value':'Y','Text':'SubchildC2a'},

				{'When':'C2','Value':'Z','Text':'SubchildC2b'},

				{'When':'D1','Value':'W','Text':'SubchildD1a'},

				{'When':'D1','Value':'X','Text':'SubchildD1b'},

				{'When':'D2','Value':'Y','Text':'SubchildD2a'},

				{'When':'D2','Value':'Z','Text':'SubchildD2b'}				

				];	

			

			function commonTemplate(item) {

				return "<option value='" + item.Value + "'>" + item.Text + "</option>"; 

			};

			function commonTemplate2(item) {

				return "<option value='" + item.Value + "'>***" + item.Text + "***</option>"; 

			};

			

			function commonMatch(selectedValue) {

				return this.When == selectedValue; 

			};

			

		</script>

Open in new window

0
 
LVL 6

Expert Comment

by:twocandles
ID: 24059905
I didn't use the cascade plugin, but what I did was "by hand".

The idea is to write an "onchange" event on the select element.
Then write a php only for getting query results, lets call it "my_php_query.php"
Inside that function write something like this (I'll write only comments):

function OnSelectElement( selectId )
{
   // make and ajax request to my_php_query.php
   // that page would return the results in either html, xml or json (the latest is the most comfortable to work with
}

Also take a look at http://www.texotela.co.uk/code/jquery/select/
It's a plugin for jQuery to work with selects, and allows you to add with a single statement the contents of a select box returned by a php.


0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24060643
thanks for the help... I'm really not good at javascript..

I've been working on it at the moment....can you see whats wrong?  I'm going with your method of using static select boxes (with Id inserted into elementid)...and then I'm trying to add options to that select box...not working.  I'm sure my code is seriously flawed!

Thanks again!

function ajaxGET(data1, page, elementid) {

        xmlhttp.open('GET', page + '?set=1&sp_id=' + data1 + '&cache=' + Math.random(), true);

        xmlhttp.onreadystatechange = function() {

            if(xmlhttp.readyState !== 4) {

                return;

            }

            else {

                if(xmlhttp.status === 200) {

                    var JSONData = eval('(' + xmlhttp.responseText + ')');

                    var placeholder = document.getElementById(elementid);

                    while(placeholder.firstChild) {

                        placeholder.removeChild(placeholder.firstChild);

                    }
 

                    //var select = document.createElement('select');

                    for(var i = 0, e = JSONData[data].length; i < e; ++i) {                       	

						placeholder.options[i] = new Option(JSONData[data][i], JSONData[data][i]);

                    }

                    placeholder.appendChild(options);

                }

                else {

                    //something baaaad happened

                }

               

            }

            

        }

        xmlhttp.send(null);

    }

Open in new window

0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24060656
my selects look like this:

<select onchange="ajaxGET(this.value, 'casc_city_area.php', 'placeholder2')" id='placeholder'>
                  <option>1</option>
</select>
0
 
LVL 6

Accepted Solution

by:
twocandles earned 500 total points
ID: 24066565
I'll attach you some code.

I used two javascript libraries: jQuery and the plugin for selects I talked to you before. You can get them here

http://jquery.com
http://www.texotela.co.uk/code/jquery/select/

<!-- Load both libraries -->

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

<script type="text/javascript" src="js/jquery.selectboxes.min.js"></script>

<script type="text/javascritp">

// The function for selecting an option

function changeSelection( obj )

{

    // Handle onselect for select1

    if( obj.id == "selectId1" )

    {

        // This statement calls "my_query.php" that returns in json format the select2 contents

        // A possible example for "my_query.php" results would be:

        // { 'value1': 'text1', 'value1': 'text1' }

        $('#selectId2').ajaxAddOption( "my_query.php", {param1:"value1"}, false );

        // Show the select2 container

        $('#select2Container').show();

    }

}

</script>
 

<!-- The selects looks like this -->

<select name="select1" id="selectId1" onchange="changeSelection( this )">

</select>

<!-- The second select starts hidden -->

<div id="select2Container" style:"display:none">

<select name="select2" id="selectId2" onchange="changeSelection( this )">

</div>

</select>

Open in new window

0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24066635
Seriously thanks for all this help!  You're a legend!

I can't get the show() to work...  notice quick correct on style: to style=

Have attached the code...
<!-- Load both libraries -->

<script type="text/javascript" src="jquery-1.3.2.js"></script>

<script type="text/javascript" src="selectboxes.min.js"></script>

<script type="text/javascritp">

// The function for selecting an option

function changeSelection( obj )

{

    // Handle onselect for select1

    if( obj.id == "selectId1" )

    {

        // This statement calls "my_query.php" that returns in json format the select2 contents

        // A possible example for "my_query.php" results would be:

        // { 'value1': 'text1', 'value1': 'text1' }

        $('#selectId2').ajaxAddOption( "my_query.php", {param1:"value1"}, false );

        // Show the select2 container

        $('#select2Container').show();

    }

}

</script>

 

<!-- The selects looks like this -->

<select name="select1" id="selectId1" onchange="changeSelection( this )">

<option value="value1">Value 1</option>

<option value="value2">Value 2</option>

</select>

<!-- The second select starts hidden -->
 
 

<div id="select2Container" style="display:none"><select name="select2" id="selectId2" onchange="changeSelection( this )"></select></div>

Open in new window

0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24066660
problem found: <script type="text/javascritp">
0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24066754
Ok last question.. It's all working really well!  

I'm trying to parse the value of the select box to the function with no success...can you see if you can spot what is wrong with this?  
<!-- Load both libraries -->

<script type="text/javascript" src="jquery-1.3.2.js"></script>

<script type="text/javascript" src="selectboxes.min.js"></script>

<script type="text/javascript">

// The function for selecting an option

function changeSelection( obj, val )

{

    // Handle onselect for select1

    if( obj.id == "selectId1" )

    {

        // This statement calls "my_query.php" that returns in json format the select2 contents

        // A possible example for "my_query.php" results would be:

        // { 'value1': 'text1', 'value1': 'text1' }

        $('#selectId2').ajaxAddOption( "my_query.php", {parm:val, false );

        // Show the select2 container

        $('#select2Container').show();

    }

}

</script>

 

<!-- The selects looks like this -->

<select name="select1" id="selectId1" onchange="changeSelection( this, this.value )">

<option value=""></option>

<option value="value1">Value 1</option>

<option value="value2">Value 2</option>

</select>

<!-- The second select starts hidden -->
 
 

<div id="select2Container" style="display:none"><select name="select2" id="selectId2" onchange="changeSelection( this, this.value )"></select></div>

Open in new window

0
 
LVL 3

Author Comment

by:Chimeraza
ID: 24066766
Ok I get the noob award! Missing }!

{parm:val, supposed to be {parm:val},

Thanks...this works like a charm and its really simple!
0
 
LVL 3

Author Closing Comment

by:Chimeraza
ID: 31565740
Thanks again!  
Corrections to this solution:
<script type="text/javascritp"> - spelling on javascript

0
 
LVL 6

Expert Comment

by:twocandles
ID: 24070575
Sorry for the misspellings... I wrote the code "on the fly" and I reviewed it a couple of times before sending, but I missed some bugs.

Glad to help and thank you for the compliments and the points. It's much more pleasant to help if your work is appreciated.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now