Jump to content

second selection box options based upon first selection box value


webguy262

Recommended Posts

I have seen this done but can't find a tutorial.

 

I have a form with two selection boxes.  One is for "make_model" the other is for "year."

 

The "make_model" options come from a bd query as follows...

 

    <form action="index_local.php" method="post" name="form1" id="form1">
        <?php 

echo'<select name="make_model"><option selected="selected">Make/Model</option>';

$res=mysql_query("select distinct make_model from photos");
if(mysql_num_rows($res)==0) echo "there is no data in table..";
else
for($i=0;$i<mysql_num_rows($res);$i++) {
$row=mysql_fetch_assoc($res);
echo"<option>$row[make_model]</option>";
}
echo'</select>';

?>

 

Right now, the "year" selection box is static as follows...

 

         
<p><select name="year">
          <option selected="selected">Year</option>
          <option value="1990">1990</option>
          <option value="1991">1991</option>
          <option value="1992">1992</option>
          <option value="1993">1993</option>
          <option value="1994">1994</option>
          <option value="1995">1995</option>
          <option value="1996">1996</option>
          <option value="1997">1997</option>
          <option value="1998">1998</option>
          <option value="1999">1999</option>
          <option value="2000">2000</option>
          <option value="2001">2001</option>
          <option value="2002">2002</option>
          <option value="2003">2003</option>
          <option value="2004">2004</option>
          <option value="2005">2005</option>
          <option value="2006">2006</option>
          <option value="2007">2007</option>
          <option value="2008">2008</option>
          <option value="2009">2009</option>
        </select>    
        
<input name="submit" type="submit" value="View" />

 

Both make_model and year are in the same db table named "photos."

 

Can I populate the "year" options (second selection box) based upon the "make_model" option selected in the first box?

 

TIA!

This can be done using either Ajax or plain php (with a page refresh):

 

Plain php approach:

$query = 'SELECT * FROM make_models ..';
$result = mysql_query($query, $db);
while ($row = mysql_fetch_assoc($result)) {
    print $row['make_model'];
}

if (!empty($_POST)) {
    $make_model = $_POST['make_model'];
    $query = 'SELECT ...';
    $result = mysql_query($query, $db);
    while ($row = mysql_fetch_assoc($result)) {
        print $result['year'];
    }
}

if (!empty($_POST['make_model']) && !empty($_POST['year'])) {
    //..
}

 

I'm not an javascript expert so maybe someone else can.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.