Problem:
How to automatically populate the options of a select menu, when the user selects an option from another menu.
We encountered this problem in the MyHouseMyStreet project. We had a select menu of streets and one of buildings within each street. We wanted that everytime the user selected a street, the buildings of that street appeared in another select menu.
Solution:
First of all, we add the select menus in the HTML code. The one containing the streets is populated from a table in the database.
The select menu for the buildings contains no options as these will be added by the javascript code.
Then we add the javascript code, which is activated everytime the user changes option in the streets’menu. The javascript sends a post request to the server passing the id of the street for which we need to retrieve the buildings and specifies the action requested (in this case to get the buildings – this is used so that you can use the php files to handle other requests as well).
The php retrieves the buildings associated to that street using the idstreet passed by the javascript and returns them in a JSON array.
The javascript receives the results and parses them.
Requirements:
jquery library
Code:
The Javascript code
//update buildings select menu as soon as a street is selected
$('#idstreet').change(function(){
var idstreet=$('#idstreet').val();
$.post("code/search_manage.php", { 'action': "getbuildings", 'idstreet': ""+idstreet+""},
function(data){
var buildings = data;
var options = '';
for (var i = 0; i <buildings.length; i++) {
options += '<option value="' + buildings[i].optionValue + '">' + buildings[i].optionDisplay + '</option>';
}
options += '<option value="all" selected>all</option>';
$("select#idbuilding").html(options);
}, "json");
return false;
});
The HTML code
<select name="idstreet" id="idstreet">
<?
$db=open_db();
$db->open("SELECT * FROM street ORDER BY street_name");
$streets=NULL;
if(!$db->eof){
while(!$db->eof){
$streets[]=$db->get_row();
}
}
foreach($streets as $street){?>
<option value="<?=$street['idstreet']?>"><?=$street['street_name']?></option>
<? }?></select>
<select name="idbuilding" id="idbuilding"></select>
The PHP server code
$action=isset($_POST['action'])?$_POST['action']:'';
if($action=="getbuildings"){
$db=open_db();
$db->open("SELECT * FROM building WHERE street_idstreet=".$_POST['idstreet']." ORDER BY bnum_name");
$buildings="[";
if(!$db->eof){
while(!$db->eof){
//$buildings['optionValue']=$db->read_field('idbuilding');
//$buildings['optionDisplay']=$db->read_field('bnum_name');
$buildings.= '{optionValue:'.$db->read_field('idbuilding').', optionDisplay: "'.$db->read_field('bnum_name').'"},';
$db->nextrow();
}
}
$db->close();
$buildings=substr($buildings,0,strlen($buildings)-1);
$buildings.="]";
echo <<<HERE_DOC
$buildings
HERE_DOC;
exit();
}