Page 1 of 1
Forms: Select options, filtered by another select option
Posted: Tue Dec 15, 2009 10:00 am
by koolsamule
Hey chaps, hope someone can help with this:
I have a PHP form, with a couple of Select menus, which are populated from two SQL tables:
// Select 1 (main colour):
// Select 2 (shade colour):
Code: Select all
Light Red
Dark Red
Light Blue
Dark Blue
Light Green
Dark Green
What I'm after is something to filter the second select option, after the first select option has been chosen
// Select 1:
// Select 2:
I'm pretty sure this is possible, but not sure how to go about it, any help would be most appreciated.
Re: Forms: Select options, filtered by another select option
Posted: Tue Dec 15, 2009 11:56 am
by AbraCadaver
AJAX. You need to add an onchange event to the first select that calls a javascript function. This function will then call a PHP file that will return the shade colours based upon the selected main colour. The javascript function can then populate the second select with the values. There are some tutorials/samples out there.
Re: Forms: Select options, filtered by another select option
Posted: Wed Dec 16, 2009 3:40 am
by koolsamule
Hi Shawn, thanks for the reply...I'm finding it hard to find a relevant tutorial, as the ones I have seen have set select values, where my select menus are dynamic:
Code: Select all
<select name="main_colour">
<option value="">Select Main Colour</option>
<?php
do {
?>
<option value="<?php echo $row_rsColourM['colourid']?>"><?php echo $row_rsColourM['colourname']?></option>
<?php
} while ($row_rsColourM = mysql_fetch_assoc($rsColourM));
$rows = mysql_num_rows($rsColourM);
if($rows > 0) {
mysql_data_seek($rsColourM, 0);
$row_rsColourM = mysql_fetch_assoc($rsColourM);
}
?>
</select>
Code: Select all
<select name="shade_colour">
<option value="">Select Shade Colour</option>
<?php
do {
?>
<option value="<?php echo $row_rsColourS['colourid']?>"><?php echo $row_rsColourS['colourname']?></option>
<?php
} while ($row_rsColourS = mysql_fetch_assoc($rsColourS));
$rows = mysql_num_rows($rsColourS);
if($rows > 0) {
mysql_data_seek($rsColourS, 0);
$row_rsColourS = mysql_fetch_assoc($rsColourS);
}
?>
</select>
Where the 'main_colour' colourid should filter the 'shade_colour' select options by FK_colourid.
Can you help or point me in the right direction?
Re: Forms: Select options, filtered by another select option
Posted: Wed Dec 16, 2009 9:02 am
by AbraCadaver
Here's the first on that came up for "php ajax select" in google:
http://www.w3schools.com/PHP/php_ajax_database.asp
Re: Forms: Select options, filtered by another select option
Posted: Wed Dec 16, 2009 9:33 am
by Eran
If the number of options is relatively small (a couple dozens to several hunderds at most), I would use plain javascript for this. Output the options as javascript value object (similar to an associative array in PHP), and use it to dynamically create the options in the second select tag on change in the first.