首页 > 代码库 > php 二级下拉框

php 二级下拉框

1,以省、市为例子,二级下拉框,先赋上页面,html部分如下:

<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">城市</label>
<div class="col-sm-10">
<select name="province" class="js-city-select1" data-value="http://www.mamicode.com/<?php echo $province_id;?>">
<option value="http://www.mamicode.com/0">请选择省份</option>
</select>
<!-- 第二个下拉框 -->
<select name="city" class="js-city-select2" data-value="http://www.mamicode.com/<?php echo $city_id;?>">
<option value="http://www.mamicode.com/0">请选择城市</option>
</select>
</div>
</div>

2,js代码如下:js代码直接复制在html页面就可以使用

<!--二级下拉列表-->
<script>
var city = <?php echo json_encode($directory) ?>
</script>
<!-- js代码(下拉框) start-->
<script>
$(function(){
var $selectFirst = $(‘.js-city-select1‘)
var $selectSecond = $(‘.js-city-select2‘)
var idFirst = 0
var idSecond = 0

var initialValueFirst = parseInt($selectFirst.data(‘value‘)) || 0
var initialValueSecond = parseInt($selectSecond.data(‘value‘)) || 0
//遍历生成第一个下拉框内容
for(var index in city){
if(initialValueFirst == city[index].id){
$selectFirst.append(‘<option value="http://www.mamicode.com/‘+city[index].id+‘" selected>‘+city[index].text+‘</option>‘)
}else{
$selectFirst.append(‘<option value="http://www.mamicode.com/‘+city[index].id+‘">‘+city[index].text+‘</option>‘)
}
}
//如果有值,自动生成下拉框(第2级)
if(initialValueSecond != 0){
for(var index in city){
if(initialValueFirst == city[index].id){
var citySecond = city[index].child

for(var index in citySecond){
if(initialValueSecond == citySecond[index].id){
$selectSecond.append(‘<option value="http://www.mamicode.com/‘+citySecond[index].id+‘" selected>‘+citySecond[index].text+‘</option>‘)
}else{
$selectSecond.append(‘<option value="http://www.mamicode.com/‘+citySecond[index].id+‘">‘+citySecond[index].text+‘</option>‘)
}
}

}
}
}
//点击第一级后生成第二级
$selectFirst.on(‘change‘,function(){
var $this = $(this)
idFirst = $this.val()
var textFirst = $this.find("option:selected").text();
for(var index in city){
if(parseInt(idFirst) == parseInt(city[index].id)){
if(city[index].child.length){
var citySecond = city[index].child
$selectSecond.html(‘<option value="http://www.mamicode.com/0">请选择</option>‘)
for(var indexSecond in citySecond){
$selectSecond.append(‘<option value="http://www.mamicode.com/‘+citySecond[indexSecond].id+‘">‘+citySecond[indexSecond].text+‘</option>‘)
}
}else{
$selectSecond.html(‘<option value="http://www.mamicode.com/0">‘+textFirst+‘</option>‘)
}
}
}
idSecond = 0
})
})
</script>

 3,php  接口部分需要给到如下格式的数据:一下赋一个json数据格式

[
{
"id": 1,
"text": "全国",
"child": [
{
"id": 12,
"text": "全国"
}
]
},
{
"id": 10,
"text": "北京",
"child": [
{
"id": 405,
"text": "北京"
}
]
},
{
"id": 11,
"text": "上海",
"child": [
{
"id": 5,
"text": "上海"
}
]
},
{
"id": 12,
"text": "天津",
"child": [
{
"id": 406,
"text": "天津"
},
{
"id": 407,
"text": "test"
}
]
},
{
"id": 13,
"text": "重庆",
"child": [
{
"id": 6,
"text": "重庆"
}
]
},
{
"id": 43,
"text": "台湾",
"child": []
}
]

json数据大家格式化一下就好,给到这个数据,下拉框需要的name值自己修改,二级下拉框完毕

 

php 二级下拉框