ComBox1(Allows Multiple Selection) ComboBox2
__________________________________ __________
Fruits
Vegetables
我有一个combobox1(允许多个选择),有项目:水果&蔬菜。
ComboBox2中的项目将根据基于ComboBox1的选择来填充。
如果选择了"Fruits",则组合框中的item应为:apple, orange,banana
ComBox1(Allows Multiple Selection) ComboBox2
__________________________________ __________
Fruits (selected) Apple
Vegetables Orange
Banana
如果既有水果又有蔬菜,那么ComboBox2的项目应该是:苹果、橘子、香蕉、萝卜、生菜。
ComBox1(Allows Multiple Selection) ComboBox2
__________________________________ __________
Fruits (selected) Apple
Vegetables (selected) Orange
Banana
Radish
Lettuce
我需要使用PHP完成此操作。谁能建议如何实现这个功能,像使用Jquery或ajax或javascript?
在现实中,我从数据库中获取两个组合框中的项目。
使用jquery,包括jquery库
<script type='text/javascript' src="http://code.jquery.com/jquery.js"></script>
然后使用以下脚本:
<script type='text/javascript'>
$(document).ready(function(){
$('#typeSelect').change(function(){
$.ajax({
url:"data.php",
data: { type: $('#typeSelect').val() },
type: "POST",
}).success(function(data){
$("#itemSelect").html(data);
});
});
});
</script>
使用这种形式:
<form>
<select id="typeSelect" multiple="multiple">
<option value="fruit">Fruit</option>
<option value="vege">Vegetables</option>
</select>
<select id="itemSelect" multiple="multiple">
</select>
</form>
在data。php中输入:
<?php
$a = array(
"fruit" => array(
"apples" => "Apples",
"bananas" => "Bananas",
"pears" => "Pears"
),
"vege" => array(
"toma" => "Tomatoes",
"cucu" => "Cucumber",
"rad" => "Radish"
)
);
foreach($_POST['type'] as $type){
foreach($a[$type] as $key => $val){
echo "<option val='{$key}'>{$val}</option>";
}
}
当然,您可以用PHP填充第一个选择框,并根据提交的值生成数组,但是为了展示如何填充选择框,我使用了一个静态数组。