dynamicly linked dropdown lists

Reply

Join Date: Oct 2008
Posts: 42
Reputation: marcmm is an unknown quantity at this point 
Solved Threads: 0
marcmm marcmm is offline Offline
Light Poster

dynamicly linked dropdown lists

 
0
  #1
Oct 10th, 2008
Hello, I am fairly new to PHP, having just started messing around with it, but I need to solve something and I would apreciate any help any of you could offer.

Here is my problem:

There's a hardware online store built using php/html and connected to a mysql database.

It has a search function that consists of three dropdown boxes, one for firm, the second for product type, and the third for subproduct.

What I want is to make those dropdown boxes interconected, so if I select something from the first list ( the firm list ) the second dropdown box will be RE-populated with only the types of products that that firm produces ( same connection between the second and third ).

As it is now, the dropdown boxes are populated by querries, like this one ( this is for the items that will be placed in the firm dropdown box ):
  1. $sql_combo_firma="SELECT DISTINCT firme.ID, firme.denfirma
  2. FROM firme, produse
  3. WHERE ((produse.id_firma=firme.ID) AND (produse.afisare='-1'))
  4. ORDER BY firme.denfirma ASC";
and this is for the product dropdown box:
  1. $sql_combo_categorie="SELECT DISTINCT categorie.ID, categorie.dencategorie
  2. FROM categorie, produse
  3. WHERE ((produse.id_categorie=categorie.ID) AND (produse.afisare='-1'))
  4. ORDER BY categorie.dencategorie ASC";
Then I proceed to execute the queries:
  1. $rez_combo_firma = MYSQL_QUERY($sql_combo_firma) OR DIE (mysql_error());
  2. $rez_combo_categorie = MYSQL_QUERY($sql_combo_categorie) OR DIE (mysql_error());
and I count how many rows the queries have:
  1. $linii_firma = MYSQL_NUM_ROWS($rez_combo_firma);
  2. $linii_categorie = MYSQL_NUM_ROWS($rez_combo_categorie);
then a proceed to populate the dropdown lists:
  1. ECHO "<SELECT NAME=combo_firma
  2. ID=combo_firma
  3. STYLE='font-family: Arial;
  4. FONT-STYLE: normal;
  5. FONT-SIZE: 11;
  6. COLOR: #000000;
  7. BACKGROUND-COLOR:#FFFFFF;
  8. BORDER-COLOR: Gray;'
  9. >";
  10.  
  11. ECHO "<OPTION VALUE = 0> Oricare </option>";
  12.  
  13. FOR ($i=0; $i<$linii_firma; $i++)
  14. {
  15. $rez_firma_ID = MYSQL_RESULT ($rez_combo_firma,$i,'ID');
  16. $rez_firma_denfirma = MYSQL_RESULT ($rez_combo_firma,$i,'denfirma');
  17.  
  18. ECHO "<OPTION VALUE = $rez_firma_ID> $rez_firma_denfirma
  19. </OPTION>";
  20. }
  21.  
  22. ECHO "</SELECT>";
and
  1. ECHO "<SELECT NAME=combo_categorie
  2. ID=combo_categorie
  3. STYLE='font-family: Arial;
  4. FONT-STYLE: normal;
  5. FONT-SIZE: 11;
  6. COLOR: #000000;
  7. BACKGROUND-COLOR:#FFFFFF;
  8. BORDER-COLOR: Gray;'
  9. >";
  10.  
  11. ECHO "<OPTION VALUE = 0> Oricare </OPTION>";
  12.  
  13. FOR ($i=0; $i<$linii_categorie; $i++)
  14. {
  15. $rez_categorie_ID = MYSQL_RESULT ($rez_combo_categorie,$i,'ID');
  16. $rez_categorie_dencategorie = MYSQL_RESULT ($rez_combo_categorie,$i,'dencategorie');
  17.  
  18. ECHO "<OPTION VALUE = $rez_categorie_ID > $rez_categorie_dencategorie </OPTION>";
  19. }
  20. ECHO "</SELECT>";
the page also has a submit button that will display all the results on another frame of the page:
  1. ECHO " <INPUT TYPE = submit
  2. NAME = buton_submit
  3. STYLE= 'FONT-FAMILY: Arial;
  4. FONT-WEIGHT: bold;
  5. FONT-STYLE: normal;
  6. FONT-SIZE: 12;
  7. COLOR:#000000;
  8. BACKGROUND-COLOR: #FFFFFF;
  9. BORDER-COLOR: Gray;'
  10. VALUE = ' : : : SEARCH : : : '>";
but I am confident that this button is not important ( the display works ok by the way, and the search works too, it's just that if you select a combination that has no resoults it will just say that there were no results. Like selecting a firm in the first box and a product in the second box that that firm dose not have. )

SO I want to make those three dropdown boxes interconected so if I select a firm in the first box, the second box will be repopulated only with the products that that firm has.

I thought about extracting the firm name ( denfirma ) and saving it in a variable and using that as a condition in the queries for the other dropdown lists. But that would not work since the queries would need to be re-executed for that to work. TO that end I thought about using the onchange event, but I don't know how to use that either.

I also searched via google for examples and several came, but they all needed addons, or other plugins to work, either they used ajax ( what ever that is ) or javascripts.

I want to know if there is any way to achieve these dynamicly linked dropdown lists without complicatted addons or classes, namelly just using php/html.

And if there isn't a way to do that I would apreciate any suggestions on how to do this because it is imperative that I solve this problem as soon as possible.
Last edited by cscgal; Oct 10th, 2008 at 4:21 pm. Reason: Added code tags
Reply With Quote Quick reply to this message  
Join Date: Sep 2007
Posts: 63
Reputation: HazardTW is an unknown quantity at this point 
Solved Threads: 2
HazardTW HazardTW is offline Offline
Junior Poster in Training

Re: dynamicly linked dropdown lists

 
0
  #2
Oct 10th, 2008
I think you need to look at client side solution to this problem at least in as much as using it for ajax calls to query the server/database, then rebuilding the drop-downs with the appropriate information.

Having the page completely reload for every menu selection change would drive even the most patient customers away with a headache.

If you have not received any useful examples by the time I get home tonight, I will post some of my examples that might give you enough information to create your own solution.

If the amount of data is not too great you might skip ajax completely and just use php to create js arrays so when the page loads, it has basically a copy of the entire database in js arrays.
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 42
Reputation: marcmm is an unknown quantity at this point 
Solved Threads: 0
marcmm marcmm is offline Offline
Light Poster

Re: dynamicly linked dropdown lists

 
0
  #3
Oct 10th, 2008
Yes indeed I figured that reloading the whole page is not a good idea cause that in the end would reset the fields too, so I don't think it's even a possible solution.

As stated before, I was thinking of using something like onchange ( if php has something like that ) to detect when a dropdown list has been modifyed. then take the selection from that list ( I have no idea how to referance a list selection in php... in clasic programing it was objectname.property... ) and store it in a variable.

The actual queries would have an if else statement that would detect if the user selected something from the lists ( the dropdown lists all default to showing everything, so if the selection is not equal to the standard, it would make a querry using the value stored in the variable mentioned earlyer in the condition. and if the user did not select anything, or he selected the default item it would do the default querry I listed in my original post. )

Then all that would be left would be a way in wich to re-trigger the querry execution ( not reload the whole page obviously, cause then all the stored data would be lost and all variables would reset to their default values ).

This is the solution I imagined for this, but I have no idea if what I desccrived above is even remptly possible.

Basicly I'm searching for a simple solution ( if one even exists ) that would not require branching in to other languages, or require the adition of plug-ins or classes. I'm trying to keep the coding as simple as possible.

I'd rather not use any external softwere or plug-in for this, so if this can be done in php it would be great.

As for the database, I don't know just what you refear to as "big". it's a hardwere store, it will have a bundle of firms, each with it's own products and subproducts. it won't have thousands of records...
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 5
Reputation: tkmc is an unknown quantity at this point 
Solved Threads: 0
tkmc tkmc is offline Offline
Newbie Poster

Re: dynamicly linked dropdown lists

 
0
  #4
Oct 10th, 2008
I had the same issue a few days ago, then figured it out.... however mine for for 2 drop downs not three.

Go to my thread about another issue that i actually posted the code for the whole page.

http://www.daniweb.com/forums/post709416-3.html

In mine if you drop down the Manager responsible list and select a manager it changes the ticket numbers in the next drop down with the numbers only allocated to that manager.

Hope this helps
Reply With Quote Quick reply to this message  
Join Date: Sep 2007
Posts: 63
Reputation: HazardTW is an unknown quantity at this point 
Solved Threads: 2
HazardTW HazardTW is offline Offline
Junior Poster in Training

Re: dynamicly linked dropdown lists

 
0
  #5
Oct 11th, 2008
Here is a quick example of using javascript to build/rebuild menus dynamically according to selections made.

There are three dropdowns but the first two do not change, the third changes based on the selections made in the first two, it could easily be extended to have different options in the second menu based on the first menu's selection.

It does not contain PHP or any other SERVER-SIDE code, how you get the data from the server into the javascript variables is up to you, either by having your PHP write the javascript variables into the javascript, or by using AJAX to get your data from the server and into a javascript variable without the user reloading the page.

I can't stress enough the difference between server-side and client-side scripting, what you want done with the menus really needs to be done client-side which means javascript.

A couple notes about javascript:
- variable for class is named vclass because class is a reserved word, if you use 'class' as a variable name your script will still work in Firefox but not in IE7.
- the array models[] uses a combination of the make and class to create an index key, each element of the models[] array is assigned a caret ^ delimted string because unlike PHP, javascript does not support multi-dimensional arrays, what a bummer

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  5. <title>Untitled Document</title>
  6.  
  7. <script type="text/javascript">
  8. <!--
  9.  
  1. // ############################################################################################# //
  2.  
  3.  
  4. var makes = new Array('Ford','Chevy','Dodge');
  5.  
  6. var vclass = new Array('SUV','Car','Pickup');
  7.  
  8. var models = new Array();
  9.  
  10. models['Ford_SUV'] = 'Escape^Explorer^Expedition';
  11. models['Ford_Car'] = 'Fusion^Mustang^Taurus';
  12. models['Ford_Pickup'] = 'Ranger^F-150^F-250 Super Duty';
  13.  
  14. models['Chevy_SUV'] = 'Suburban^TrailBlazer^Tahoe';
  15. models['Chevy_Car'] = 'Impala^Malibu^Corvette';
  16. models['Chevy_Pickup'] = 'Colorado^Silverado^Avalanche';
  17.  
  18. models['Dodge_SUV'] = 'Durango^Nitro';
  19. models['Dodge_Car'] = 'Avenger^Caliber^Charger';
  20. models['Dodge_Pickup'] = 'Dakota^Ram';
  21.  
  22.  
  23. function menu_change(menu){// MAKE CLASS MODEL
  24.  
  25. // only need to create this menu once since it will not change
  26. // it will be made when this function is called via onLoad="menu_change('ALL')" in the BODY element
  27. if (menu == 'ALL'){
  28.  
  29. // get the select object for the make menu
  30. var make_menu = document.getElementById('make_menu');
  31.  
  32. // strip the select element of any options it may currently have
  33. while ( make_menu.options.length ){
  34. make_menu.remove(make_menu.options[0]);
  35. }
  36.  
  37. // itterate through the global array makes that contain our vehicle mfgrs name
  38. for ( var i = 0; i < makes.length; i++ ){
  39.  
  40. // create an option element
  41. var newOpt=document.createElement('option');
  42.  
  43. // make the option text equal the make of the vehicle
  44. newOpt.text=makes[i];
  45.  
  46. // try to add the option element to the select element
  47. try{
  48.  
  49. make_menu.add(newOpt,null); // standards compliant
  50.  
  51. }catch(ex){
  52.  
  53. make_menu.add(newOpt); // IE only
  54.  
  55. }
  56.  
  57. // now that we have our new option element we can give it a value, the same as the text in this case
  58. make_menu.options[i].value = makes[i];
  59.  
  60. }
  61.  
  62. // make the first option in the new drop-down list the selected one
  63. make_menu.selectedIndex = 0;
  64.  
  65. }
  66.  
  67. // this will build the CLASS menu, it only needs to be re-built when MAKE is changed and when page loads
  68. // since classes is same for all makes, this menu does not need to be rebuilt, but if you had different classes
  69. // options for the different makes and created arrays the same as I did for models, then this section could be
  70. // modified to affect the menu changes you would need
  71. if (menu == 'MAKE' || menu == 'ALL'){
  72.  
  73. // get the select object for the class menu
  74. var class_menu = document.getElementById('class_menu');
  75.  
  76. // strip the select element of any options it may currently have
  77. while ( class_menu.options.length ){
  78. class_menu.remove(class_menu.options[0]);
  79. }
  80.  
  81. // itterate through the global array class that contain our vehicle classes
  82. for ( var i = 0; i < vclass.length; i++ ){
  83.  
  84. // create an option element
  85. var newOpt=document.createElement('option');
  86.  
  87. // make the option text equal the class
  88. newOpt.text=vclass[i];
  89.  
  90. // try to add the option element to the select element
  91. try{
  92.  
  93. class_menu.add(newOpt,null); // standards compliant
  94.  
  95. }catch(ex){
  96.  
  97. class_menu.add(newOpt); // IE only
  98.  
  99. }
  100.  
  101. // now that we have our new option element we can give it a value, the same as the text in this case
  102. class_menu.options[i].value = vclass[i];
  103.  
  104. }
  105.  
  106. // make the first option in the new drop-down list the selected one
  107. class_menu.selectedIndex = 0;
  108.  
  109. }
  110.  
  111. // this will rebuild the model menu, it needs to be built on page load, and rebuild whenever MAKE or CLASS has changed
  112. if (menu == 'CLASS' || menu == 'MAKE' || menu == 'ALL'){
  113.  
  114. // get the select object for the model menu
  115. var model_menu = document.getElementById('model_menu');
  116.  
  117. // strip the select element of any options it may currently have
  118. while ( model_menu.options.length ){
  119. model_menu.remove(model_menu.options[0]);
  120. }
  121.  
  122. // the structure for our models array is: models['<MAKE>_<CLASS>'] = '<model>^<model>^<model>'
  123. // so we need to know what the current selected make and class is
  124. // so we can access the appropriate models array to get our list of models
  125.  
  126. // get the select element for our makes menu
  127. var current_make = document.getElementById('make_menu');
  128. // get the value of the currently selected option of the menu
  129. current_make = current_make.options[current_make.selectedIndex].value;
  130.  
  131. // get the select element for our class menu
  132. var current_class = document.getElementById('class_menu');
  133. // get the value of the currently selected option of the menu
  134. current_class = current_class.options[current_class.selectedIndex].value;
  135.  
  136. // create our string index key for the models array we are looking for
  137. var index = current_make + '_' + current_class;
  138.  
  139. // now that we know what models array to get we can get the '^' delimited string value and turn it into an array
  140. var model_list = models[index].split('^');
  141.  
  142. // itterate through our local array model_list that contain our vehicle models for the currently selected make and class
  143. for ( var i in model_list ){
  144.  
  145. // create an option element
  146. var newOpt=document.createElement('option');
  147.  
  148. // make the option text equal the model of the vehicle
  149. newOpt.text=model_list[i];
  150.  
  151. // try to add the option element to the select element
  152. try{
  153.  
  154. model_menu.add(newOpt,null); // standards compliant
  155.  
  156. }catch(ex){
  157.  
  158. model_menu.add(newOpt); // IE only
  159.  
  160. }
  161.  
  162. // now that we have our new option element we can give it a value, the same as the text in this case
  163. model_menu.options[i].value = model_list[i];
  164.  
  165. }
  166.  
  167. // make the first option in the new drop-down list the selected one
  168. model_menu.selectedIndex = 0;
  169.  
  170. }
  171.  
  172. return;
  173. }
  174. // ############################################################################################# //
  1. -->
  2. </script>
  3.  
  4. </head>
  5.  
  6. <body onLoad="javascript:menu_change('ALL')">
  7.  
  8. <div>
  9.  
  10. <select id="make_menu" onChange="menu_change('MAKE')">
  11. <option></option>
  12. </select>
  13.  
  14. <select id="class_menu" onChange="menu_change('CLASS')">
  15. <option></option>
  16. </select>
  17.  
  18. <select id="model_menu">
  19. <option></option>
  20. </select>
  21.  
  22. </div>
  23.  
  24. </body>
  25. </html>
Reply With Quote Quick reply to this message  
Join Date: Sep 2007
Posts: 63
Reputation: HazardTW is an unknown quantity at this point 
Solved Threads: 2
HazardTW HazardTW is offline Offline
Junior Poster in Training

Re: dynamicly linked dropdown lists

 
0
  #6
Oct 11th, 2008
I went ahead and added different second-menu options based on the first menu selection:

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  5. <title>Untitled Document</title>
  6.  
  7. <script type="text/javascript">
  8. <!--
  9.  
  10. // ############################################################################################# //
  11.  
  12. //////////////////////////////////////////////////////////////////////////////////////////////
  13. // THIS SECTION COULD BE WRITTEN BY PHP FROM DATABASE QUERIES
  14. //
  15. var makes = new Array('Ford','Chevy','Dodge');
  16.  
  17. var vclass = new Array();
  18.  
  19. vclass['Ford'] = 'SUV^Pickup^Muscle^Cars';
  20. vclass['Chevy'] = 'SUV^Pickup^Sport^Cars';
  21. vclass['Dodge'] = 'SUV^Pickup^Muscle^Economy^Van';
  22.  
  23. var models = new Array();
  24.  
  25. models['Ford_SUV'] = 'Escape^Explorer^Expedition';
  26. models['Ford_Cars'] = 'Fusion^Taurus';
  27. models['Ford_Pickup'] = 'Ranger^F-150^F-250 Super Duty';
  28. models['Ford_Muscle'] = 'Mustang';
  29.  
  30. models['Chevy_SUV'] = 'Suburban^TrailBlazer^Tahoe';
  31. models['Chevy_Cars'] = 'Impala^Malibu';
  32. models['Chevy_Pickup'] = 'Colorado^Silverado^Avalanche';
  33. models['Chevy_Sport'] = 'Corvette';
  34.  
  35. models['Dodge_SUV'] = 'Durango^Nitro';
  36. models['Dodge_Economy'] = 'Caliber';
  37. models['Dodge_Pickup'] = 'Dakota^Ram';
  38. models['Dodge_Van'] = 'Caravan';
  39. models['Dodge_Muscle'] = 'Charger';
  40. //
  41. // END SECTION TO BE WRITTEN BY PHP
  42. //////////////////////////////////////////////////////////////////////////////////////////////
  43.  
  44. function menu_change(menu){// MAKE CLASS MODEL
  45.  
  46. // only need to create this menu once since it will not change
  47. // it will be made when this function is called via onLoad="menu_change('ALL')" in the BODY element
  48. if (menu == 'ALL'){
  49.  
  50. // get the select object for the make menu
  51. var make_menu = document.getElementById('make_menu');
  52.  
  53. // strip the select element of any options it may currently have
  54. while ( make_menu.options.length ){
  55. make_menu.remove(make_menu.options[0]);
  56. }
  57.  
  58. // itterate through the global array makes that contain our vehicle mfgrs name
  59. for ( var i = 0; i < makes.length; i++ ){
  60.  
  61. // create an option element
  62. var newOpt=document.createElement('option');
  63.  
  64. // make the option text equal the make of the vehicle
  65. newOpt.text=makes[i];
  66.  
  67. // try to add the option element to the select element
  68. try{
  69.  
  70. make_menu.add(newOpt,null); // standards compliant
  71.  
  72. }catch(ex){
  73.  
  74. make_menu.add(newOpt); // IE only
  75.  
  76. }
  77.  
  78. // now that we have our new option element we can give it a value, the same as the text in this case
  79. make_menu.options[i].value = makes[i];
  80.  
  81. }
  82.  
  83. // make the first option in the new drop-down list the selected one
  84. make_menu.selectedIndex = 0;
  85.  
  86. }
  87.  
  88. // this will build the CLASS menu, it only needs to be re-built when MAKE is changed and when page loads
  89. if (menu == 'MAKE' || menu == 'ALL'){
  90.  
  91. // get the select element for our makes menu
  92. var current_make = document.getElementById('make_menu');
  93. // get the value of the currently selected option of the menu
  94. current_make = current_make.options[current_make.selectedIndex].value;
  95.  
  96. //vclass['Dodge']
  97. // get the array of classes for the selected make
  98. var vclasses = vclass[current_make].split('^');
  99.  
  100. // get the select object for the class menu
  101. var class_menu = document.getElementById('class_menu');
  102.  
  103. // strip the select element of any options it may currently have
  104. while ( class_menu.options.length ){
  105. class_menu.remove(class_menu.options[0]);
  106. }
  107.  
  108. // itterate through the global array class that contain our vehicle classes
  109. for ( var i = 0; i < vclasses.length; i++ ){
  110.  
  111. // create an option element
  112. var newOpt=document.createElement('option');
  113.  
  114. // make the option text equal the class
  115. newOpt.text=vclasses[i];
  116.  
  117. // try to add the option element to the select element
  118. try{
  119.  
  120. class_menu.add(newOpt,null); // standards compliant
  121.  
  122. }catch(ex){
  123.  
  124. class_menu.add(newOpt); // IE only
  125.  
  126. }
  127.  
  128. // now that we have our new option element we can give it a value, the same as the text in this case
  129. class_menu.options[i].value = vclasses[i];
  130.  
  131. }
  132.  
  133. // make the first option in the new drop-down list the selected one
  134. class_menu.selectedIndex = 0;
  135.  
  136. }
  137.  
  138. // this will rebuild the model menu, it needs to be built on page load, and rebuild whenever MAKE or CLASS has changed
  139. if (menu == 'CLASS' || menu == 'MAKE' || menu == 'ALL'){
  140.  
  141. // get the select object for the model menu
  142. var model_menu = document.getElementById('model_menu');
  143.  
  144. // strip the select element of any options it may currently have
  145. while ( model_menu.options.length ){
  146. model_menu.remove(model_menu.options[0]);
  147. }
  148.  
  149. // the structure for our models array is: models['<MAKE>_<CLASS>'] = '<model>^<model>^<model>'
  150. // so we need to know what the current selected make and class is
  151. // so we can access the appropriate models array to get our list of models
  152.  
  153. // get the select element for our makes menu
  154. var current_make = document.getElementById('make_menu');
  155. // get the value of the currently selected option of the menu
  156. current_make = current_make.options[current_make.selectedIndex].value;
  157.  
  158. // get the select element for our class menu
  159. var current_class = document.getElementById('class_menu');
  160. // get the value of the currently selected option of the menu
  161. current_class = current_class.options[current_class.selectedIndex].value;
  162.  
  163. // create our string index key for the models array we are looking for
  164. var index = current_make + '_' + current_class;
  165.  
  166. // now that we know what models array to get we can get the '^' delimited string value and turn it into an array
  167. var model_list = models[index].split('^');
  168.  
  169. // itterate through our local array model_list that contain our vehicle models for the currently selected make and class
  170. for ( var i in model_list ){
  171.  
  172. // create an option element
  173. var newOpt=document.createElement('option');
  174.  
  175. // make the option text equal the model of the vehicle
  176. newOpt.text=model_list[i];
  177.  
  178. // try to add the option element to the select element
  179. try{
  180.  
  181. model_menu.add(newOpt,null); // standards compliant
  182.  
  183. }catch(ex){
  184.  
  185. model_menu.add(newOpt); // IE only
  186.  
  187. }
  188.  
  189. // now that we have our new option element we can give it a value, the same as the text in this case
  190. model_menu.options[i].value = model_list[i];
  191.  
  192. }
  193.  
  194. // make the first option in the new drop-down list the selected one
  195. model_menu.selectedIndex = 0;
  196.  
  197. }
  198.  
  199. return;
  200. }
  201. // ############################################################################################# //
  202.  
  203.  
  204. -->
  205. </script>
  206.  
  207. </head>
  208.  
  209. <body onLoad="javascript:menu_change('ALL')">
  210.  
  211. <div>
  212.  
  213. <select id="make_menu" onChange="menu_change('MAKE')">
  214. <option></option>
  215. </select>
  216.  
  217. <select id="class_menu" onChange="menu_change('CLASS')">
  218. <option></option>
  219. </select>
  220.  
  221. <select id="model_menu">
  222. <option></option>
  223. </select>
  224.  
  225. </div>
  226.  
  227. </body>
  228. </html>
Last edited by HazardTW; Oct 11th, 2008 at 7:32 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 42
Reputation: marcmm is an unknown quantity at this point 
Solved Threads: 0
marcmm marcmm is offline Offline
Light Poster

Re: dynamicly linked dropdown lists

 
0
  #7
Oct 13th, 2008
I thank you all for taking the time to repply, but as I said I am very new to the whole web programming thing. I just whent over basic PHP and html. I haven't done any javascript, or dabbled with the use of other plug-ins like this ajax everybody seems to mentione. That's why I asked if it was possible to achieve this dynamism using just php alone.

I guess it's not possible to do that in php. SO I guess I have to branch out in to javascript too. I would like to experiment with the example you provided, but embarassed as it makes me, I don't even know how to make it run.

Thous far I have been using a softwere called wampserver that incloudes bolth apache and mysql. ANd with php/html it was relativelly easy as I ran everything through localhost/filename.extension ( be it php or html ). BUt I honestly have no clue how to run files that contain javascripts. I know there's jscript files with the js extension... but that dosen't work because if I save the file like that the browser will just display the code. ( by the way i'm using notepad to write my code ).

So if you could point me in the right direction I would apreciate it...

Linking objects dynamicly seemed like such a simple thing at first, and it's turning in to a real nightmere the more you learn about it.
Last edited by marcmm; Oct 13th, 2008 at 10:47 am.
Reply With Quote Quick reply to this message  
Join Date: Sep 2007
Posts: 63
Reputation: HazardTW is an unknown quantity at this point 
Solved Threads: 2
HazardTW HazardTW is offline Offline
Junior Poster in Training

Re: dynamicly linked dropdown lists

 
0
  #8
Oct 13th, 2008
JavaScript is run in the browser, it can be written into the HTML document between script tags, or an external js file can be linked to the page so it loads into the browser when the page loads.

One thing to remember is that the parts of your js that are not inside functions will run linear to the page, take the following example:

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  5. <title>Untitled Document</title>
  6. <script type="text/javascript">
  7. <!--
  8.  
  9. var mydiv_1 = document.getElementById('div_1');
  10.  
  11. function get_div(){
  12.  
  13. var mydiv_2 = document.getElementById('div_2');
  14.  
  15. }
  16.  
  17.  
  18. -->
  19. </script>
  20. </head>
  21.  
  22. <body onLoad="javascript:get_div()">
  23.  
  24.  
  25. <div id="div_1"></div>
  26.  
  27. <div id="div_2"></div>
  28.  
  29.  
  30. </body>
  31. </html>

This line: var mydiv_1 = document.getElementById('div_1');
is not in a function, it is run in sequence with the document and would fail to get the element with id='div_1' because that element doesn't exists in the browser yet, it is further down the document.

The function get_div() however is not executed until after the page is loaded via an onload event in the <body> tag, so when it executes the element 'div_2' does exist.

Also remember that your js functions need to be triggered by some event to execute, be it onload, onunload, onclick, onmouseover, etc...

W3Schools is a good place to get the fundamentals of javascript.

I don't know if this will help or only confuse, but I rewrote the dynamic liked menus to be more automatic, the number of menus is limited only to how many you build data for.
The functions do not care how many menus there are.
Just copy this and paste it as an html document and open it in your browser:
(I put in a lot of comments, but as I said above it might just be more confusing)
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  5. <title>Untitled Document</title>
  6.  
  7. <script type="text/javascript">
  8. <!--
  9.  
  10. // ############################################################################################# //
  11.  
  12.  
  13. // The number of menus you can have is dynamic, just list the menu names in order in the menu_names array
  14. // then create the items array, making sure you build items for every menu in menu_names array.
  15. // make the first items array key equal the first menu name, in this example it is "Make"
  16. // your first menu contents should be formatted like this:
  17. // items['<first menu name>'] = '<main menu item 1>^<main menu item 2>^<main menu item 3>';
  18. //
  19. // all menu items for the second menu are formatted like this:
  20. // items['<main menu item selected>'] = '<second menu item 1>^<second menu item 2>^<second menu item 3>';
  21. // you do this for every item in main menu
  22. //
  23. // all menu items for the third menu are formatted like this:
  24. // items['<main menu item selected>_<second menu item selected>'] = '<third menu item 1>^<third menu item 2>^<third menu item 3>';
  25. // you create one of these for every combination of main menu, and second menu.
  26. //
  27. // using this pattern you can create as many linked menus as you need
  28. //
  29. // all menu items strings must be delimited by a caret ^
  30. // ie. items['Make'] = 'Ford^Chevy^Dodge';
  31. // Ford, Chevy, and Dodge are menu items stored as a ^ delimited string in items['Make']
  32. //
  33. // name of each menu in the dynamic menu system
  34. // these must be in order
  35. // var menu_names = new Array('<menu 1 name>','<menu 2 name>','<menu 3 name>','<menu 4 name>', ... '<menu 9 name>');
  36. var menu_names = new Array('Make','Class','Model','Color');
  37.  
  38. var items= new Array();
  39.  
  40. // contents of first menu
  41. items['Make'] = 'Ford^Chevy^Dodge';
  42.  
  43. //
  44. // the index keys must match the values entered for the menus
  45. // example:
  46. // var menu_names = new Array('Make','Class','Model','Color');
  47. // items['Make'] = 'Ford^Chevy^Dodge';
  48. // items['Ford'] = 'SUV^Pickup^Muscle^Cars';
  49. // items['Ford_SUV'] = 'Escape^Explorer^Expedition';
  50. //
  51. // the "Make" in items['Make'] must match the menu name in menu_names, we use "Make" here because it is our top-level menu(menu 1)
  52. // the "Ford" in items['Ford'] must match the "Ford" in items['Make'] = 'Ford^Chevy^Dodge';
  53. // the "SUV" in items['Ford_SUV'] must match the "SUV" in items['Ford'] = 'SUV^Pickup^Muscle^Cars';
  54. //
  55. // all index keys, ie. 'Ford_SUV_Expedition', must be seperated by underscores
  56. //
  57.  
  58. // contents of second menu based on selected value of first menu
  59.  
  60. // if Ford is selected in first menu, then second menu contains:
  61. items['Ford'] = 'SUV^Pickup^Muscle^Cars';
  62.  
  63. // if Chevy is selected in first menu, then second menu contains:
  64. items['Chevy'] = 'SUV^Pickup^Sport^Cars';
  65.  
  66. // if Dodge is selected in first menu, then second menu contains:
  67. items['Dodge'] = 'SUV^Pickup^Muscle^Economy^Van';
  68.  
  69.  
  70.  
  71. // contents of third menu based on selection of menu 1 and menu 2
  72.  
  73. // if menu 1 is Ford
  74.  
  75. // and menu 2 is SUV, then menu 3 is:
  76. items['Ford_SUV'] = 'Escape^Explorer^Expedition';
  77.  
  78. // and menu 2 is Cars, then menu 3 is:
  79. items['Ford_Cars'] = 'Fusion^Taurus';
  80.  
  81. // and menu 2 is Pickup, then menu 3 is:
  82. items['Ford_Pickup'] = 'Ranger^F-150^F-250 Super Duty';
  83.  
  84. // and menu 2 is Muscle, then menu 3 is:
  85. items['Ford_Muscle'] = 'Mustang';
  86.  
  87.  
  88.  
  89. // if menu 1 is Chevy
  90.  
  91. // and menu 2 is SUV, then menu 3 is:
  92. items['Chevy_SUV'] = 'Suburban^TrailBlazer^Tahoe';
  93.  
  94. // and menu 2 is Cars, then menu 3 is:
  95. items['Chevy_Cars'] = 'Impala^Malibu';
  96.  
  97. // and menu 2 is Pickup, then menu 3 is:
  98. items['Chevy_Pickup'] = 'Colorado^Silverado^Avalanche';
  99.  
  100. // and menu 2 is Sport, then menu 3 is:
  101. items['Chevy_Sport'] = 'Corvette';
  102.  
  103.  
  104.  
  105. // if menu 1 is Dodge
  106.  
  107. // and menu 2 is SUV, then menu 3 is:
  108. items['Dodge_SUV'] = 'Durango^Nitro';
  109.  
  110. // and menu 2 is Economy, then menu 3 is:
  111. items['Dodge_Economy'] = 'Caliber';
  112.  
  113. // and menu 2 is Pickup, then menu 3 is:
  114. items['Dodge_Pickup'] = 'Dakota^Ram';
  115.  
  116. // and menu 2 is Van, then menu 3 is:
  117. items['Dodge_Van'] = 'Caravan';
  118.  
  119. // and menu 2 is Muscle, then menu 3 is:
  120. items['Dodge_Muscle'] = 'Charger';
  121.  
  122.  
  123.  
  124. // contents of the fourth menu based on the selections in menu 1(Make), menu 2(Class), and menu 3(Model)
  125.  
  126. // if menu 1 is Ford and menu 2 is SUV:
  127.  
  128. // and menu 3 is Escape, then menu 4 is:
  129. items['Ford_SUV_Escape'] = 'Red^White^Black';
  130.  
  131. // and menu 3 is Explorer, then menu 4 is:
  132. items['Ford_SUV_Explorer'] = 'Blue^Yellow^Green';
  133.  
  134. // and menu 3 is Expedition, then menu 4 is:
  135. items['Ford_SUV_Expedition'] = 'Red^White^Black';
  136.  
  137.  
  138. // if menu 1 is Ford and menu 2 is Cars:
  139.  
  140. // and menu 3 is Fusion, then menu 4 is:
  141. items['Ford_Cars_Fusion'] = 'Blue^Yellow^Green';
  142.  
  143. // and menu 3 is Taurus, then menu 4 is:
  144. items['Ford_Cars_Taurus'] = 'Red^White^Black';
  145.  
  146.  
  147. // if menu 1 is Ford and menu 2 is Pickup:
  148.  
  149. // and menu 3 is Ranger, then menu 4 is:
  150. items['Ford_Pickup_Ranger'] = 'Blue^Yellow^Green';
  151.  
  152. // and menu 3 is F-150, then menu 4 is:
  153. items['Ford_Pickup_F-150'] = 'Red^White^Black';
  154.  
  155. // and menu 3 is F-250 Super Duty, then menu 4 is:
  156. items['Ford_Pickup_F-250 Super Duty'] = 'Blue^Yellow^Green';
  157.  
  158.  
  159. // if menu 1 is Ford and menu 2 is Muscle:
  160.  
  161. // and menu 3 is Mustang, then menu 4 is:
  162. items['Ford_Muscle_Mustang'] = 'Red^White^Black';
  163.  
  164.  
  165. // follow the same pattern with the other "Make_Class_Model" menu possiblities
  166. items['Chevy_SUV_Suburban'] = 'Blue^Yellow^Green';
  167. items['Chevy_SUV_TrailBlazer'] = 'Red^White^Black';
  168. items['Chevy_SUV_Tahoe'] = 'Blue^Yellow^Green';
  169.  
  170. items['Chevy_Cars_Impala'] = 'Red^White^Black';
  171. items['Chevy_Cars_Malibu'] = 'Blue^Yellow^Green';
  172.  
  173. items['Chevy_Pickup_Colorado'] = 'Red^White^Black';
  174. items['Chevy_Pickup_Silverado'] = 'Blue^Yellow^Green';
  175. items['Chevy_Pickup_Avalanche'] = 'Red^White^Black';
  176.  
  177. items['Chevy_Sport_Corvette'] = 'Blue^Yellow^Green';
  178.  
  179. items['Dodge_SUV_Durango'] = 'Red^White^Black';
  180. items['Dodge_SUV_Nitro'] = 'Blue^Yellow^Green';
  181.  
  182. items['Dodge_Economy_Caliber'] = 'Red^White^Black';
  183.  
  184. items['Dodge_Pickup_Dakota'] = 'Blue^Yellow^Green';
  185. items['Dodge_Pickup_Ram'] = 'Red^White^Black';
  186.  
  187. items['Dodge_Van_Caravan'] = 'Blue^Yellow^Green';
  188.  
  189. items['Dodge_Muscle_Charger'] = 'Red^White^Black';
  190.  
  191.  
  192. // recursive function to extract the index for items[] for the current menu level
  193. // example: menu_names = new Array(0=>'Make',1=>'Class',2=>'Model',3=>'Color');
  194. // menu_names[2] = "Model"
  195. // to get a list of models we need to know the "Make" and "Class" selected
  196. // if "Make" is "Ford" and "Class" is "SUV"
  197. // we want items["Ford_SUV"] to get a list of Ford SUV's
  198. // since the menu we want is "Model" and it's index in the menu_names array is 2
  199. // the value sent to this function is 2
  200. // on the initial call it gets the value of the menu immediately above it menu_names[2-1=1] = "Class"
  201. // which we said for our example is "SUV"
  202. // since m is greater than 1 the function calls itself recursively with m-1 until m == 1
  203. // with m = 2 - 1 = 1 the functions does not call itself again but instead returns the
  204. // value of the selected index of the menu named menu_names[m=(1-1)=0] = "Make" which we said was "Ford"
  205. // so with the recursive call returning "Ford"
  206. // and the initial call returning <recursive call> + '_' + "SUV"
  207. // our new index for items[] = "Ford_SUV"
  208. // items["Ford_SUV"] = 'Escape^Explorer^Expedition'
  209. // which will be the contents of our new "Model" menu
  210. // menu levels "m" are:
  211. // 0 == menu 1(this menu will not call this function)
  212. // 1 == menu 2
  213. // 2 == menu 3
  214. // 3 == menu 4
  215. // and so on...
  216. function build_option_index(m){
  217.  
  218. // make sure we are dealing with a number vs string
  219. m = Number(m);
  220.  
  221. // get the menu that is directly above the currently passed menu level
  222. var tlm = document.getElementById(menu_names[m-1] + '_menu');
  223.  
  224. // test to see if this menu has a selected option, and if so that it is not a negative number
  225. if( tlm.selectedIndex && tlm.selectedIndex >= 0 ){
  226.  
  227. // if we have a selected menu option, record it's index
  228. var selected_index = tlm.selectedIndex;
  229.  
  230. }else{
  231.  
  232. // if we do not have a valid selected option for this menu, we use index 0
  233. // which will be the first option available for the menu we are looking at
  234. var selected_index = 0;
  235.  
  236. }
  237.  
  238. // get the value of the selected menu option
  239. var current_value = tlm.options[selected_index].value;
  240.  
  241. if( m <= 1 ){
  242. alert('last recursive call returning: ' + current_value);
  243. // really this is m==1 but I use m<=1 just to make sure we don't get any errors
  244. // with m == 1 this means we are at menu 2 and the value we are returning is the
  245. // value of the selected option for menu 1 ( document.getElementById(menu_names[m-1] + '_menu'); ), our top-level menu
  246. // last itteration, will return the value of the selected top-level menu item
  247. return current_value;
  248.  
  249. }else{
  250. alert('making recursive call: <recursive call> + "_" + ' + current_value);
  251. // if we are not at menu 2 ( m==1 ) yet, then we append the current menu - 1 selected value
  252. // to the returned value of a recursive call to this function using the next menu up ( m-1 )
  253. // using the underscore to seperate the values
  254. return build_option_index(m-1) + '_' + current_value;
  255.  
  256. }
  257.  
  258. }
  259.  
  260. // function to add the select elements to the document
  261. // only requires an element with id="dynamic_menu_wrapper" be present in the document
  262. // to append the new select elements to
  263. function build_menus(){
  264.  
  265. // get the document element that will hold our menus
  266. var wrapper = document.getElementById('dynamic_menu_wrapper');
  267.  
  268. // itterate through all menu names in menu_names array
  269. for( var m in menu_names ){
  270.  
  271. // format of the select elements we are creating:
  272. // <select id="<current menu name>_menu" onChange="menu_change(this.id)">
  273.  
  274. // create the select element
  275. var sel = document.createElement('select');
  276.  
  277. // create a text node to go before the select element to print the current menu name
  278. var t = document.createTextNode(menu_names[m] + ': ');
  279.  
  280. // set the id property of the select element
  281. sel.id = menu_names[m] + '_menu';
  282.  
  283. // set the onChange function of the select element
  284. // needed to trigger the functions to rebuild necessary lower-level menus
  285. sel.onchange = function(){menu_change(this.id);};
  286.  
  287. // add the text element to the document element that will hold our menus
  288. wrapper.appendChild(t);
  289. // add the select element now
  290. wrapper.appendChild(sel);
  291.  
  292. }
  293.  
  294. // all menus have been created and added to the document
  295. // call menu_change with argument 'ALL' to build the options for all menus
  296. menu_change('ALL');
  297.  
  298. }
  299.  
  300. // function called when any menu value is changed so we can build new lower-level menus
  301. // than the menu being changed
  302. function menu_change(menu){
  303.  
  304. // strip '_menu' from the element ID to get current menu name
  305. menu = menu.replace('_menu','');
  306.  
  307. // initialize menu_index to be greater than existing indices
  308. var menu_index = menu_names.length;
  309.  
  310. // itterate through all menus
  311. for( m in menu_names ){
  312.  
  313. // check menu against current index, if match then set menu_index
  314. // used to determine if the changing menu is a higher menu than the
  315. // current index, meaning it needs to be re-built
  316. if( menu == menu_names[m] ) menu_index = m;
  317.  
  318. // only build menu if current index 'm' is higher than menu_index
  319. // so we only rebuild menus that are lower than the changed menu
  320. if( m > menu_index || menu == 'ALL' ){
  321.  
  322. alert('rebuilding menu: ' + menu_names[m]);
  323.  
  324. // if m==0 then we are currently itterating over the top-level menu (menu 1)
  325. // so we don't call the recursive function to get our items[] index
  326. // option_list_index will be used to get items['<option_list_index>']
  327. if( m == 0 ){
  328.  
  329. // current itteration is menu 1 so we set the option_list_index to
  330. // menu_names[0] which is the first menu in menu_names array
  331. // and items['<menu 1 name>'] == the only set of values for menu 1
  332. // ie. items['Make'] = 'Ford^Chevy^Dodge';
  333. var option_list_index = menu_names[0];
  334.  
  335. }else{
  336.  
  337. // if we are past menu 1, the top-level menu then we need to
  338. // use the build_option_index() function to return the index key
  339. // we need for the current menu level
  340. // ie. option_list_index could be "Ford_SUV_Expedition"
  341. // which would mean we were building options for the fourth level menu
  342. // who's value in our example are:
  343. // items['Ford_SUV_Expedition'] = 'Red^White^Black';
  344. var option_list_index = build_option_index(m);
  345. alert('back from recursive function with index: ' + option_list_index);
  346.  
  347. }
  348.  
  349. // example: items['Ford_SUV_Expedition'] = 'Red^White^Black';
  350. // split the resulting string at ^ and get an array of 'Red','White','Black'
  351. // for our menu options
  352. var current_items = items[option_list_index].split('^');
  353.  
  354. // get the current menu select element
  355. var current_menu = document.getElementById(menu_names[m]+'_menu');
  356.  
  357. // strip the select element of any options it may currently have
  358. while ( current_menu.options.length ){
  359.  
  360. current_menu.remove(current_menu.options[0]);
  361.  
  362. }
  363.  
  364. // itterate through the current_items array
  365. for ( var i = 0; i < current_items.length; i++ ){
  366.  
  367. // create an option element
  368. var newOpt=document.createElement('option');
  369.  
  370. // make the option text equal the current item
  371. newOpt.text=current_items[i];
  372.  
  373. // try to add the option element to the select element
  374. try{
  375.  
  376. current_menu.add(newOpt,null); // standards compliant
  377.  
  378. }catch(ex){
  379.  
  380. current_menu.add(newOpt); // IE only
  381.  
  382. }
  383.  
  384. // now that we have our new option element we can give it a value, the same as the text in this case
  385. current_menu.options[i].value = current_items[i];
  386.  
  387. }
  388.  
  389. // make the first option in the new drop-down list the selected one
  390. current_menu.selectedIndex = 0;
  391.  
  392. }
  393.  
  394.  
  395. }
  396.  
  397. return;
  398.  
  399. }
  400. // ############################################################################################# //
  401.  
  402.  
  403. -->
  404. </script>
  405.  
  406. </head>
  407.  
  408. <body onLoad="javascript: build_menus()">
  409.  
  410. <div id="dynamic_menu_wrapper">
  411.  
  412.  
  413. </div>
  414.  
  415. </body>
  416. </html>

For some reason there are <b></b> tags being inserted into the code at:
<body onLoad="javascript: build_menus()">
Between javascript and the colon, they should not be there.
Last edited by HazardTW; Oct 13th, 2008 at 6:30 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 42
Reputation: marcmm is an unknown quantity at this point 
Solved Threads: 0
marcmm marcmm is offline Offline
Light Poster

Re: dynamicly linked dropdown lists

 
0
  #9
Oct 14th, 2008
Ok, well I understood how your example works... basicly, I'm still having problem with the syntax, and recursivity is an anoyance ( didn't really like it back when I was doing C++, don't like it now either, but hey, if it gets the job done... ).

Now, I would have one more question reguarding this example, it works out perfectly and it's just what I'm looking for, so I'm going to try and apply this to my problem, but there's a catch, I have noticed that you actually whent and hard-coded all the possible combos. Now it's preatty simple with so few options, but I would imagine that the amount of code would increase to staggering proportions for more options, not to mentione that each time the database is changed ( adding new fields, removing or modifying existing fields ) would mean that one would have to go in the page code too and modify the code acording to the database changes.

Just upkeeping the table of possible combos would be a titanic job. There must be a way in wich to automate that process, so that the combos would be generated automatically reguardless of what data you are importing from the database.

SO far, as I posted in my original topic, I'm gettign the data out of the database through queries, wich I am storing in arrays, and then asigning the values of the arrays directly in to the menues ( I'm guessing that this code would work just as well from a .php file as it dose from an .html file, no? ), now obviously if the menues are to be linked, this process won't work. At this point I can only imagine asigning the data of each dropdown list to a separate string, then somehow use a system of FORs combined with a strlength to create these combos automatically. But I doubt that would work since something like that would still require the table of combos you described in the example above just to remember wich suboptions belong to wich options and so on...

I'm stumped as to how to work around this...

ANy ideas?
Last edited by marcmm; Oct 14th, 2008 at 12:21 pm.
Reply With Quote Quick reply to this message  
Join Date: Sep 2007
Posts: 63
Reputation: HazardTW is an unknown quantity at this point 
Solved Threads: 2
HazardTW HazardTW is offline Offline
Junior Poster in Training

Re: dynamicly linked dropdown lists

 
0
  #10
Oct 14th, 2008
The idea behind my last example is that when the page is loaded by the client, the PHP would build ALL the js variables from your database queries by echoing them into the js part of the document.
The method to extract your data from the database will be completely dependent on your database structure.

Can you give me an example of how your database is structured, ie. tables, columns in those tables, which data becomes a menu, which data becomes selections of those menu's, etc.
You can use dummy names and values, just the structure is important,and how it relates to the menus.
Maybe I can build a php script for you.
Last edited by HazardTW; Oct 14th, 2008 at 4:07 pm.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the PHP Forum
Thread Tools Search this Thread



Tag cloud for PHP
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC