?
Solved

Getting values of a select tag, when selected...

Posted on 2003-03-18
11
Medium Priority
?
337 Views
Last Modified: 2008-02-01
I have to make two pull-dowm select menus, one containing the name of a course and the other the number of the class...

The first select menu gets the values from a mySQL database, with a select statement like this...
SELECT nmCOurse FROM cadCourse; and it displays as options on a select pull-down menu...

The next menu, is supposed to get the information selected in the last menu, and show a list of classes available for that course (kinda like those sites that when you select you state, it shows a list of citys in that state). So what I tried was to make a PHP function that received a variable with the selection... Like this...

<?
     getClasses($db,$course);

?>

The function with the value from the select menu (name=course) should return a list of classes for that particular course, but the variable is epmpty, I echoed it and it shows nothing...

My question is how do I do it? I need to make a menu that depends on a choice of another menu, kinda like refreshing the second menu depending on the choice of the first menu.

Can anyone help?
Thanks
0
Comment
Question by:fstani
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +2
11 Comments
 

Expert Comment

by:joshence
ID: 8161991
well - if you trust Javascript you can do something with that.  (search javascript.internet.com) but you will have to write PHP code to write javascript to update your webpage.  (if you don't mind that way I'll see if I can help you out  a little)

The way I would try to do it:
You will have to have your list of classes, when selected you can add a pop up to pick the class number, or submit to another page that will list the class numbers to choose from.  

This second way will be much more reliable and my recommendation.  but both will work.  let me know which you would like
0
 

Expert Comment

by:joshence
ID: 8162003
oh ya - out of my curious nature...what is the code behind function getClasses($db,$course)
0
 
LVL 15

Expert Comment

by:VGR
ID: 8162822
if you want the second menu to dynamically adapt itself to the choice in the first, you've no other choice than jscript as joshence wrote.

I can show you some PHP code that writes jscript code ;-)

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:fstani
ID: 8163978
joshence, I don't mind using jscript, I only wish to see it working for now... ...about the code, well what I'm doing is trying to adapt a code that was already implemented...

The older code, had only one Select menu, where all the classes of all courses where displayed in one big menu, and it was dificult to find the right classes...

Okay, the old function is the following:

function getClasses($db, $cdClass) {
     $query = "SELECT C.cdClass, Co.deCourse FROM cadCourses Co, cadClasses C WHERE C.cdCourse=Co.cdCourse ORDER BY Co.deCourse asc";
     $result = mysql_query ($query, $bd);
     if (!$result) { echo 'Error: Cannot query database';}
     while($register = mysql_fetch_array ($result)) {
          $str = '';
          if($register[cdClass]==$cdClass) {
               $str = 'SELECTED';
          }
          echo "<OPTION VALUE=$register[cdClass] $str>($register[cdClass]) - $register[deCourse]</OPTION>";
     }
}

With that function I made a split, one to get the Course, and another to get the Class... so I had two functions:

function getCourses($bd, $scdCourses) {
     $query = "SELECT * FROM cadCourses ORDER BY deCourse asc";
     $result = mysql_query ($query, $bd);
     if (!$result) { echo 'Error: Cannot query database';}
     $acdCourses = explode (",", $scdCourses);
     while($register = mysql_fetch_array ($result)) {
          $str = '';
          for($i=0; $i<sizeof($acdCourses); $i++) {
               if ($register[cdCourse] == $acdCourses[$i])
                    { $str = 'SELECTED'; }
          }
          echo "<OPTION VALUE=$register[cdCourse] $str>$register[deCourse]</OPTION>";
     }
}

This function returns various options of courses to a select tag.

and:

function getClasses($bd, $deCourse) {
     $query = "SELECT C.cdClass FROM cadCourses Co, cadClasses C WHERE Co.deCourse=$deCourse and C.cdCourse=Co.cdCourse";
     $result = mysql_query ($query, $bd);
     if (!$result) { echo 'Error: Cannot query database';}
     while($register = mysql_fetch_array ($result)) {
          echo "<OPTION VALUE=$register[cdClass]>$register[cdClass]</OPTION>";
     }
}

This is the function I implemented... ...and the Html of the select tags is like this...

<TR>
<TD WIDTH=190 HEIGHT=20 ALIGN=RIGHT VALIGN=TOP CLASS="tittle11p">
     Course:
</TD>
<TD WIDTH=306 HEIGHT=20 ALIGN=LEFT VALIGN=TOP>
&nbsp;<SELECT NAME="deCourse" CLASS="box200">
      <OPTION VALUE="">Select</OPTION>
       <?
          getCourses($bd, '');
       ?>
</SELECT>
</TD>
</TR>
                                                           <TR>
<TD WIDTH=190 HEIGHT=20 ALIGN=RIGHT VALIGN=TOP CLASS="tittle11p">
      Class Code:
</TD>
<TD WIDTH=306 HEIGHT=20 ALIGN=LEFT VALIGN=TOP>
&nbsp;<SELECT NAME="cdClass" CLASS="box200">
<OPTION VALUE="">Select</OPTION>
     <?
          getClasses($bd,'$deCourse');
        ?>
</SELECT>
</TD>                                        </TR>

So basically, if you put all the functions and codes together you will see that I call for the function with the parameter from the other select...

Well, anyways, this is what I did... ...but since I'm in the process of learning PHP (I program in Delphi, Java, C) I'm still a little ways to go...

Anyways, if you could share with me the jscript code for the menus, I'll be happy...

Thanks

P.s.: I Hope it is not too long :)
0
 

Accepted Solution

by:
joshence earned 200 total points
ID: 8164314
well if you like to modify code this would be the one to work with:

http://javascript.internet.com/forms/auto-drop-down.html

I'm sure you can get it to do what you want.  If You really need me to I can punch out some psudo code or if need be actual code.  But I have a feeling you can handel it.  this JS is pretty easy to follow.  

----look at the script before reading this----
all you would have to do is open up javascript (<script language='javascript'>
<?
then run your functions but have the output print in the format of the array.  
?>
</script>

The down side to this is that to load the page you have to download each class and all of its class numbers into a javascript load.  So if you are looking for fast download time this is not the way to go.  other wise let me know if you need further assistence.

Joshua
0
 
LVL 2

Expert Comment

by:bobsledbob
ID: 8164530

You don't need javascript to do this so long as you're ok with your user pressing the submit button in between the choice of courses and classes.  I assume this is what you're doing right?

Also, be sure to have error_reporting(E_ALL); at the top of your script.  You might be missing some warnings if you don't have this set (like for instance, the fact that $deCourse might be null because you've got register globals off???)

I think you've got your basic logic down.  You've just got some bug that isn't being shown or something.

You could probably clean up your code a little to.  Only one course can be selected at a time, right?  If so, you could clean up like this by removing your whole inner for loop.

function getCourses($db) {
  $query = "SELECT * FROM cadCourses ORDER BY deCourse asc";
  $result = mysql_query ($query, $bd);
  if (!$result) { echo 'Error: Cannot query database';}

  while($register = mysql_fetch_array ($result)) {
    if (isset($_POST["deCourse"]) && $_POST["deCourse"] == $register[cdCourse])
      $str = "SELECTED";
    else
      $str = "";

    echo "<OPTION VALUE=$register[cdCourse] $str>$register[deCourse]</OPTION>";
  }

}

Your class selection should probably be wrapped with a if isset as well:

<?php
  if (isset($_POST["deCourse"]))
    getClasses($db, $_POST["deCourse"]);
?>

Anyway, like I said:

1)  use: error_reporting(E_ALL);
2)  the user needs to submit between course and class selection.
3)  E_ALL will likely find errors with your variables, in which case don't forget to check for them before calling them with: if (isset ());

Hope this helps.

Adam

0
 
LVL 15

Expert Comment

by:VGR
ID: 8164761
As you don't answer my proposition, here's some code I use :

// this is in HEAD stuff after title, meta-tags etc
echo <<<EOS
<script language="Javascript">
<!--
  // spicifique modhles et marques
  var globModelesNb = new Array();
EOS;
$d = dir("./trophees");
$i=0;
$locmodeles=array();
while($entry=$d->read()) {
  if (($entry<>'.') and ($entry<>'..')) {
    $i++;
    $locmodeles[$i]=$entry;
    echo "\nvar Modeles$i = new Array(\"\"";
    $j=0;
    $d2 = dir("./trophees/$entry");
    while($entry2=$d2->read()) {
      if (($entry2<>'.') and ($entry2<>'..')) {
        $j++;
        echo ",\"$entry2\"";
      } // if modhle
    } // while
    $d2->close();
    echo ");\n";
    echo "globModelesNb[$i]=$j;\n";
  } // if marque
} // while
$d->close();
// final
echo "\nvar globModeles = new Array(Modeles1";
for ($j=2;$j<=$i;$j++) echo ",Modeles$j";
echo ");\n";
//exemple  var Modeles1 = new Array("","safrane","clio");
//exemple  var Modeles2 = new Array("","nioumodhle");
//exemple  globModelesNb[1]=2;
//exemple  globModelesNb[2]=1;

echo <<<EOS
//debug
//for (i in globModeles) {
//  for (j in globModeles[i]) {
//    alert("iliment "+i+","+j+"="+globModeles[i][j]);
//  }
//}

function monindex(par)
{
var valeurloc = 0;
switch (par)
{
EOS;
for ($j=1;$j<=$i;$j++) echo "case \"".$locmodeles[$j]."\":\nvaleurloc=$j;\nbreak\n";
echo <<<EOS
default:
  valeurloc=0;
}
return valeurloc;
}

function changement(obj,Value)
{
  // classique
  var dest   = obj.form.elements["FModele"];
  var marque = Value;

//alert(dest.options.length+' ` effacer');
  for (i=dest.options.length-1;i>=0;i--) dest.remove(i);
//alert(Value+' est index marque');
  Value=monindex(Value);
  zob=globModelesNb[Value];
//alert(zob+' ` ajouter');
  nouvelleOption = new Option();
  nouvelleOption.text = "Nouveau";
  nouvelleOption.value = "Nouveau";
  dest.add(nouvelleOption, 0);
//alert("nouveau ajouti en position 0");
  for (i=1; i<=zob;i++) {
  zobu=globModeles[Value-1][i];
//alert("on essaie d'ajouter "+zobu+" en position "+i);
    nouvelleOption = new Option();
    nouvelleOption.text = zobu;
    nouvelleOption.value = zobu;
    dest.add(nouvelleOption, i);
//alert(zobu+' ajouti en position '+i);
  }
  return true;
}
// -->
</script>
EOS;
echo "</HEAD>";

[snip]
echo "<FORM METHOD=\"POST\" name=saisie ACTION=$PHP_SELF ENCTYPE=\"multipart/form-data\">";
echo "<table bgColor=#000000 border=0 cellPadding=0 cellSpacing=5 >";
echo "<tr><td>Origine : Marque <SELECT NAME=FMarque width=12 size=1 onchange=\"changement(this,saisie.FMarque.options[selectedIndex].value);\">";
echo "<option value=0 selected>choix marque</option>";
ListeMarques($locMarque,FALSE);
$locNewMarque='si Nouvelle...';
echo "</SELECT><BR><center><INPUT border=0 TYPE=text NAME=FNewMarque VALUE=\"$locNewMarque\" SIZE=12 MAXLENGTH=12></center></td>";
echo "<td>Modhle <SELECT NAME=FModele width=12 size=1>";
echo "<option value=0 selected>choisissez marque</option>";
ListeModeles($locModele,$locMarque,FALSE);
$locNewModele='si Nouveau...';
echo "</SELECT><BR><center><INPUT border=0 TYPE=text NAME=FNewModele VALUE=\"$locNewModele\" SIZE=12 MAXLENGTH=12></center></td><td>Motorisation <INPUT border=0 TYPE=text NAME=FMotorisation VALUE=\"$locMotorisation\" SIZE=16 MAXLENGTH=20></td></tr>";
echo "</table>";
?>

and here are the Liste* functions used above
function ListeMarques($par,$isRech) { // avec "Nouvelle" en sus
  if ($isRech) echo "<OPTION VALUE=\"toutes\"".(($par=='')?' SELECTED':'').">toutes";
  else echo "<OPTION VALUE=\"Nouvelle\">Nouvelle (priciser)";
  $d = dir("./trophees");
  $i=0;
  while($entry=$d->read()) {
    if (($entry<>'.') and ($entry<>'..')) echo "<OPTION VALUE=\"$entry\"".(($par==$entry)?' SELECTED':'').">$entry";
  } // while
  $d->close();
} // ListeMarques Procedure

function ListeModeles($parModele, $parMarque,$isRech) { // avec "Nouveau" en sus
  if ($isRech) echo "<OPTION VALUE=\"tous\"".(($parModele=='')?' SELECTED':'').">tous";
  else echo "<OPTION VALUE=\"Nouveau\">Nouveau (priciser)";
  $d = dir("./trophees/$parMarque");
  while($entry=$d->read()) {
    if (($entry<>'.') and ($entry<>'..')) echo "<OPTION VALUE=\"$entry\"".(($parModele==$entry)?' SELECTED':'').">$entry";
  } // while
  $d->close();
} // ListeModeles Procedure

so basically this works as : (this is for cars)
-the Modeles are taken from the Marque selected (initial values come from the DB)
-whenever the user changes Marque (brand), the Modeles (Models) are updated in the listbox associated, via jscript.
-the Marques and subsequent Modeles are taken from the filesystem, as I have a filetree like :
.
./renault
./renault/r21
./renault/r5
./peugeot
./peugeot/405
./peugeot/406
./peugeot/504
./mercedes
./mercedes/classeC
./mercedes/190
[etc]
but they could come from a DB table, of course

Hope this helps
0
 
LVL 15

Expert Comment

by:VGR
ID: 8164764
yooooo EE accepts the accents again ! Good work pals ! :D
0
 
LVL 1

Author Comment

by:fstani
ID: 8169251
Everyone, it will take a lil while to look up the answers..., so if you please have a little patience I'll be going through your answers...

And if anyone has a doubt, all I want is to make two select tags, one static and another dynamic, which depends on the choice of the static one, and auto reloads itself when a choice is selected...

bobsledbob: I don't want a submit button between select tags...

VGR & joshense: I'll be looking up (implementing) your answers, and probably tomorrow I'll see what works best. Thanks...
0
 
LVL 33

Expert Comment

by:snoyes_jw
ID: 11935473
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I will leave the following recommendation for this question in the Cleanup topic area:
    Accept: joshence {http:#8164314}

Any objections should be posted here in the next 4 days. After that time, the question will be closed.

snoyes_jw
EE Cleanup Volunteer
0

Featured Post

WordPress Tutorial 2: Terminology

An important part of learning any new piece of software is understanding the terminology it uses. Thankfully WordPress uses fairly simple names for everything that make it easy to start using the software.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

770 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