更新:更改選項以反映這是一個select2下拉列表中的新信息。
試試這個:(見https://jsfiddle.net/yrLbvs5g/的工作演示)
<select id="customer">
</select>
<select id="ticket">
</select>
<script type="text/javascript">
$(document).ready(function() {
// data array all 'customer' options
var customers = [
{ id: '0', text: '- Customers -'},
{ id: '123', text: 'customer 123'},
{ id: '124', text: 'customer 124'},
{ id: '125', text: 'customer 125'},
{ id: '126', text: 'customer 126'},
{ id: '127', text: 'customer 127'},
];
// populate customer dropdown with options from array
$("#customer").select2({
data: customers
});
// data array for all 'ticket' options
var tickets = [
{ id: '0', text: '- Tickets -', customer: ''},
{ id: '1', text: 'ticket 1', customer: '123'},
{ id: '2', text: 'ticket 2', customer: '123'},
{ id: '3', text: 'ticket 3', customer: '124'},
{ id: '4', text: 'ticket 4', customer: '126'},
{ id: '5', text: 'ticket 5', customer: '126'},
];
// function to populate tickets both on load and on change of 'customer'
jQuery.fn.setTickets = function(reset) {
// if flagged to reset, this will empty the select2() options for 'ticket' below
if (! reset) { var reset = false; }
// get currently-selected customer value
var customer = $(this).val();
// build new data array using 'tickets' as our data source, but then excluding
// options that don't match the 'customer' value above
var new_tickets = [];
for (var i=0; i < tickets.length; i++) {
// includes ticket if no customer is selected ('0') or if the ticket itself has
// no id/value (id '0' = '- Tickets -', or our blank title option), or if the
// customer matches the 'customer' attribute of the tickets data array
if (customer=='0' || tickets[i].id=='0' || customer==tickets[i].customer) {
new_tickets.push(tickets[i]);
}
}
// reset previously-populated select2() options
if (reset) {
$("#ticket").select2('destroy').empty();
}
// populate tickets with new 'new_tickets' data array, and trigger the change to
// tell select2() to re-build options
$("#ticket").select2({ data: new_tickets }).trigger('change');
}
// on document load, build tickets with no reset
$("#customer").setTickets();
// on customer change, re-populate tickets with reset passed in to erase previous ticket options
$("#customer").change(function(){
$(this).setTickets(1);
});
});
</script>
我更新我的回答如下,以反映您選擇2的情況。如果它適合您,您能否將其標記爲已接受? – David