[英]Jquery select2 ajax chained selects
要求: <select1>
包含一些选项(占位符文本=“选择新的或二手车辆”) <select2>
禁用,没有选项(占位符文本=“选择制造商”)
<select1>
user选择填充结果为1的选项<select2>
利用Jquery Select2插件
我已经链接选择正常工作,正确填充select2,也使用select2插件
问题:我希望占位符文本在获得结果时说“找到5个结果”我希望占位符文本说“找到0个结果”时没有结果并返回到禁用状态目前,占位符文本更改为首先选择,当重新选择它时会搞乱select2占位符
HTML:
//<select1>
<select name='category_id' id='category_id'>
<option value='1'>New</option>
<option value='2'>Used</option>
</select>
//<select2>
<select name='make_id' id='make_id'><option value=''></option></select>
//javascript
<script type='text/javascript'>
$(document).ready(function() {
$('#category_id').select2({
placeholder: 'Select new or used Vehicles',
allowClear: true
});
$('#make_id').select2({
placeholder: 'Select Manufacturer',
allowClear: true
});
$('#category_id').change(function() {
var selectedCategory = $('#category_id option:selected').val();
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType: 'html',
data: {
a: 'dropDownsHome',
c: selectedCategory
},
success: function(txt){
//no action on success, its done in the next part
}
}).done(function(data){
//get JSON
data = $.parseJSON(data);
//generate <options from JSON
var list_html = '';
$.each(data, function(i, item) {
list_html += '<option value='+data[i].id+'>'+data[i].make+'</option>';
});
//replace <select2 with new options
$('#make_id').html(list_html);
//set to enabled|disabled
if (data.length > 1) {
$('#make_id').select2('enable', true); //enable form
}else{
$('#make_id').select2('enable', false); //disable form
}
//change placeholder text
$('#make_id').select2({placeholder: data.length +' results'});
})
});
});
</script>
//来自ajax.php的JSON结果(如果没有结果,则返回false)[{“id”:“1”,“make”:“Foton”},{“id”:“4”,“make”:“现代 “},{” ID “:” 5" , “使”: “KIA”},{ “ID”: “2”, “使”: “质子”},{ “ID”: “2”,”令 “:” 质子 “},{” ID “:” 3" , “作”: “塔塔”},{ “ID”: “3”, “作”: “塔塔”},{ “ID”:” 6" , “作”: “丰田”}]
尝试升级插件,
我试过3.4.0版本启用和禁用工作正常,还添加
list_html += ' <option value=""></option>';
上面跟着代码,然后占位符也会显示..我已经对下面编辑过的代码进行了修改
//generate <options from JSON
var list_html = '';
list_html += ' <option value=""></option>';
$.each(data, function(i, item) {
list_html += '<option value='+data[i].id+'>'+data[i].make+'</option>';
});
//replace <select2 with new options
$('#make_id').html(list_html);
//set to enabled|disabled
if (data.length > 1) {
$('#make_id').select2('enable', true); //enable form
$('#make_id').select2({placeholder: data.length +' results'});
}else{
$('#make_id').select2('enable', false); //disable form
$('#make_id').select2({placeholder: 0 +' results'});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.