在下面的代码片段中,我假设您有一个数组,其中包含作为对象的数据库行,我将其命名为 $results;
编辑:如何获取您的查询对象:
http ://www.php.net/manual/en/mysqli-result.fetch-object.php
我首先收集用于创建组合框的数据:
$combobox_data = array();
$results = mysqli_query("SELECT * FROM TABLE");
//create a multi dimensional array with names per category
while($row = mysqli_fetch_object($results)){
$combobox_data[$row->Category][] = $row->Name;
}
$category_combobox_html = "";
$name_combo_boxes_html = "";
//create category combo_box
foreach($combobox_data as $category=>$names){
//Add category option to category combo-box
$category_combobox_html .= '<option value="'.$category.'">'.$category.'</option>';
//Create Names combo-box for this category
$name_combo_boxes_html .= '<select id="'.$category.'" name="'.$category.'" class="hidden_combobox">';
//loop names, to add Names in the combo-box for this category
foreach($names as $name){
$name_combo_boxes_html .= '<option value="'.$name.'">'.$name.'</option>';
}
//end your combo box for this category
$name_combo_boxes_html .= '</select>';
}
你的 CSS
<style type="text/css" media="screen">
.hidden_combobox{
display:none;
}
</style>
你的html
<select name="categories" id="categories">
<?php echo $category_combobox_html; ?>
</select>
<?php echo name_combo_boxes_html ;?>
你的 javascript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
//when you select something from category box
$("#categories").change(function(){
//get selected category
var selectedValue = $(this).find(":selected").val();
//hide all nameboxes
$('.namebox').each(function(){
$(this).hide();
});
//show combobox for this select
$('#'+selectedValue).show();
});
</script>
你的结果将是这样的:
除非您选择与 combo_box 匹配的类别,否则所有名称组合框都将被隐藏
<select name="categories" id="categories">
<option value="Airport">Airport</option>
<option value="College">College</option>
<option value="busstop">busstop</option>
</select>
<select id="Airport" name="Airport" class="namesbox hidden_combobox">
<option value="ABC">ABC</option>
<option value="XYZ">XYZ</option>
</select>
<select id="College" name="College" class="namesbox hidden_combobox">
<option value="a1">a1</option>
<option value="b1">b1</option>
<option value="b2">b2</option>
</select>
<select id="busstop" name="busstop" class="namesbox hidden_combobox">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>