项目中前端使用的是bootstrap前端框架,遇到div动态添加select下拉框时无法显示问题
项目中遇到个需求,图中根据field里的选择free shipping时在下图condition动态生成下选框,其他选择为图中所示:
直接上代码:body里面
<div class="form-group">
<div class="col-md-1 col-sm-6 col-xs-12" >Qriteria</div>
<div class="col-md-2 col-sm-6 col-xs-12" >
<select id="field1" name="cntryIds" size="10"
class="form-control col-md-1 col-xs-12 selectpicker"
required="required" οnchange="selectOnchange(this)">
<option>Free Shipping</option>
<option selected="selected">Item Price</option>
<option>Item Total Price</option>
<option>SpeedPak</option>
</select>
</div>
<div class="col-md-3 col-sm-6 col-xs-12" id="doubleText">
</div>
<div class="col-md-3 col-sm-6 col-xs-12">
<input type="text" class="form-control col-md-7 col-xs-12" placeholder="Number Input">
</div>
</div>
script里面的函数
function selectOnchange(obj) {
//alert(obj.selectedIndex);
var selectIndex = obj.selectedIndex;
if(selectIndex == 0 || selectIndex== 3){
document.getElementById("doubleText").innerHTML='<select id="condition1" name="cntryIds" size="10"'+
'class="form-control col-md-3 col-xs-12 selectpicker" required="required">'+
'<option selected="selected">Yes</option> <option>No</option> </select>';
}else{
document.getElementById("doubleText").innerHTML='<input type="text" style="width: 30%;" placeholder="Min" >' +
'<label style="width: 20%;margin-left: 20%">-</label>' +
'<input type="text" style="width: 30%;" placeholder="Max" >';
}
}
然后结果如下图:
这时select选框失效了,想了半天,查了下资料终于解决,通过添加如下两行代码:
$('#condition1').selectpicker('refresh');
$('#condition1').selectpicker('render');
function selectOnchange(obj) {
//alert(obj.selectedIndex);
var selectIndex = obj.selectedIndex;
if(selectIndex == 0 || selectIndex== 3){
document.getElementById("doubleText").innerHTML='<select id="condition1" name="cntryIds" size="10"'+
'class="form-control col-md-3 col-xs-12 selectpicker" required="required">'+
'<option selected="selected">Yes</option> <option>No</option> </select>';
$('#condition1').selectpicker('refresh');
$('#condition1').selectpicker('render');
}else{
document.getElementById("doubleText").innerHTML='<input type="text" style="width: 30%;" placeholder="Min" >' +
'<label style="width: 20%;margin-left: 20%">-</label>' +
'<input type="text" style="width: 30%;" placeholder="Max" >';
}
}
这时前端结果如下:
完美解决bootstrap下拉框select无法显示的问题