我有两个选择输入,一个用于#customer,另一个用于#ticket,它们具有以下选项结构:
<option value="123">
<option value="" customer="123">
因此,故障单选择中的每个选项都有相关客户到故障单记录
我希望能够隐藏客户属性不等于所选客户价值的所有票证选项,反之亦然,因此选择正确的客户价值,其中票证选项的客户属性等于客户选项的值< / p>
对于第一部分,我的代码是:
$("#customer").change(function(){
if($(this).val() !== $("#ticket").find('option:selected').attr('customer')) {
}
});
并在里面,如果我尝试过:
$("#ticket").not("[customer*=" + $(this).val() + "]").hide();
和
$("#ticket option[customer=" + $(this).val() + "]").hide();
但都没有按预期工作。
答案 0 :(得分:1)
更新:更改选项以反映有关此选项下拉列表的新信息。
试试这个:(请参阅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>