这里我用的是bootstrap框架,所以有些是引用的bootstrap的类,非boostrap开发可以省略。
HTML代码:
<form role="form">ou
<!--for test, there have three selectboxs-->
<div class="form-group ">
<select class="form-control selectbox">
<option>please choose your favorites fruit</option>
</select>
</div>
<div class="form-group ">
<select class="form-control selectbox2">
<option>please choose your favorites fruit</option>
</select>
</div>
<div class="form-group ">
<select class="form-control selectbox3">
<option>please choose your favorites fruit</option>
</select>
</div>
</form>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
一、只有一个select时:
JQuery代码:
$(document).ready(function)(){
$.getJSON("SelectData URL here",function(data1){//this is for getting option values
for(var i = 0; i < data1['data'].length;i++){
//data is the name from php(open PHP URL in browers)
$('.selectbox').append('<option'+data1['data'][i].ID+'>'+
data1['data'][i].name+'</option>');//set up option's values
}
});
$('.selectbox').change(function(){
var selectBox1 = $('.selectbox').val().trim();
$('tbody').empty();
$.getJSON("TableData URL here",{selectbox1:ID1},function(data2){
//ID1 is the data match with checked option's values
for(var j = 0; j < data2['data'].length;j++){
$('tbody').append("<tr><td>"+data2['data'][j].ID+
"</td><td>"+data['data'][j].name+
"</td><td>"+data['data'][j].address+"</td></tr>");
}
});
})
});
二、select二级联动+刷新
select二级联动跟只有一个select的时候差不多,只需要做一点小小的改动——在change事件下加一行代码:
$('.selectbox').change(function(){
var selectBox1 = $('.selectbox').val().trim();//the first selectbox
var selectBox2 = $('.selectbox2').val.trim();//the second selectbox
$('tbody').empty();
$.getJSON("TableData URL here",{selectBox1:ID1,selectBox2:ID2},function(data2){
//about ID1 & ID2,this you can get from URL in the end of URL,such as: ?ID=1
for(var j = 0; j < data2['data'].length;j++){
$('tbody').append("<tr><td>"+data2['data'][j].ID+
"</td><td>"+data['data'][j].name+
"</td><td>"+data['data'][j].address+"</td></tr>");
}
});
})
});
知道了一级联动和二级联动的做法,不难知道多级联动应该怎么做。
这是我第一次做select联动,如果有问题,欢迎大家交流。