我有两个下拉列表category
和subs
。我想当用户更改category
dorpdown时,第二个下拉列表将从服务器重新加载:
<select id="cats">
@foreach($all_cat as $c)
<option value="{{$c->id}}">{{$c->title}}</option>
@endforeach
</select>
<br />
<select id="subs">
</select>
我的jquery代码:
$('#cats').on('change', function() {
var cats = $('#cats').val();
$('#subs option').remove();
$.post('{{base_url()}}cp/VitrinSection/getCategoriesByAjax' , {cats:cats , subs:0 , subs2:0 } , function(data){
$("#subs").append(data);
console.log(data);
})
});
$('#subs').on('change', function() {
});
一切正常但在使用append
函数后,我的subs
下拉列表中添加了一个空选项替代!
我的控制台日志:
<option value='1'>A<option><option value='2'>B<option><option value='3'>c<option><option value='4'>D<option>
我的服务器代码:
public function getCategoriesByAjax(){
$posts = $this->input->post();
if($posts['cats'] != 0){
$cat_id = $posts['cats'];
$subs = $this->M_Vitrin->getSubCategories();
$value = '' ;
foreach($subs as $s ){
if($s->ads_cat_id == $cat_id){
$value .= "<option value='$s->id'>$s->title<option>";
}
}
echo $value;
}else if($posts['subs'] != 0){
}else{
}
}
从服务器获取数据后:
<select id="subs">
<option value="1">A</option>
<option></option>//?
<option value="2">B</option>
<option></option>//?
<option value="3">C</option>
<option></option>//?
<option value="4">D</option>
<option></option> //?
</select>
答案 0 :(得分:1)
public function getCategoriesByAjax(){
$posts = $this->input->post();
if($posts['cats'] != 0){
$cat_id = $posts['cats'];
$subs = $this->M_Vitrin->getSubCategories();
$value = '' ;
foreach($subs as $s ){
if($s->ads_cat_id == $cat_id){
$value .= "<option value='$s->id'>$s->title</option>"; //close properly
}
}
echo $value;
}else if($posts['subs'] != 0){
}else{
}
}
从上面的代码中你需要关闭选项正确更改
if($s->ads_cat_id == $cat_id){ $value .= "<option value='$s->id'>$s->title<option>"; }
关闭正确更改为$value .= "<option value='$s->id'>$s->title</option>";