我正在尝试使用select2和jQuery 1.9.1并选择2 3.3.0来实现我想象的是一个相当基本的用例...我想用基于另一个select2控件的状态的选项填充select2控件
我有以下内容:
<div>
<select id="master" name="master">
<option value=1>a</option>
<option value=2>b</option>
</select>
</div>
<div>
<input type="hidden" id="detail" name="detail" data-placeholder="No options until master chosen">
</select>
<script src="jquery-1.9.1.js"></script>
<script src="select2-3.3.0/select2.js"></script>
<script>
var a = [];
var b = [];
for (var i = 0; i < 20; i++) {
a.push({id: i, text: "a" + i});
b.push({id: i, text: "b"+ i});
}
$(document).ready( function () {
$("#master").select2().on('change', function() {
console.log("master changed: " + $("#master").val())
var right_one = a;
if($("#master").val() == 2) right_one = b;
$("#detail").removeClass('select2-offscreen').select2({data:right_one})
console.log("right_one: " + right_one)
})
})
<div>
<select id="master" name="master">
<option value=1>a</option>
<option value=2>b</option>
</select>
</div>
<div>
<input type="hidden" id="detail" name="detail" data-placeholder="No options until master chosen">
</select>
<script src="jquery-1.9.1.js"></script>
<script src="select2-3.3.0/select2.js"></script>
<script>
var a = [];
var b = [];
for (var i = 0; i < 20; i++) {
a.push({id: i, text: "a" + i});
b.push({id: i, text: "b"+ i});
}
$(document).ready( function () {
$("#master").select2().on('change', function() {
console.log("master changed: " + $("#master").val())
var right_one = a;
if($("#master").val() == 2) right_one = b;
$("#detail").removeClass('select2-offscreen').select2({data:right_one})
console.log("right_one: " + right_one)
})
})
修改 This answer显示控件消失的原因。关于这个实现,我还有一些问题:
答案 0 :(得分:1)
第二个选择#detail将不再起作用,你只能点击选项,但如果你尝试输入几个字符,你会看到发生了什么。
答案 1 :(得分:0)
Mabye这样的事情:
<script>
var a = [];
var b = [];
for (var i = 0; i < 20; i++) {
a.push({id: i, text: "a" + i});
b.push({id: i, text: "b"+ i});
}
$(document).ready( function () {
//set up default data, should work without one too
$('#detail').data('select2_values', []);
$('#detail').select2({
allowClear: true,
width: '150px',
placeholder: 'No options until master chosen',
query: function (query) {
var data = {results: []};
if (query.term == '')
{
data.results = $('#detail').data('select2_values');
}
query.callback(data);
},
initSelection : function (element, callback) {
var data = $(element).data('select2_values');
if (typeof(data)!='object') data = [];
callback(data);
},
data: $(this).data('select2_values')
}).select2('disable');
$('#master').select2({
allowClear: true,
width: '150px'
}).on("change", function(e) {
var right_one = a;
if ($('#master').select2('val') == 2) right_one = b;
$("#detail").data('select2_values', right_one);
//Remove previous value if any
$("#detail").select2('val','');
//If you want to select some vaoue you can use next line
//$("#detail").select2('data', right_one[0]);
//Enable 2nd box
$("#detail").select2('enable');
});
});
</script>
在chrome + win32上测试