Reputation: 2092
I have a dropdown list of companies. I also have some dropdown lists of contacts (primary_contact, sales_contact, insurance_contact) which all belong to class "contact". When the company changes, I update the list of available contacts using the following code:
$('#company').change(function () {
var company = $(this)[0].value.toString();
$.getJSON('<%= ResolveUrl("~/Subcontracts/CompanyContacts/") %>' + company, null, function (data) {
$('.contact').empty().append("<option value=''>**Select Contact**</option>");
$.each(data, function (index, optionData) {
$('.contact').append("<option value='" + optionData.contact_id + "'>" + optionData.contact_name + "</option>");
});
});
});
Some contacts are valid for multiple subsidiaries. If the previously selected contact shows up in the new contact list, I would like for them to still be selected. So, if the previously selected sales_contact is in the list, select them. Same for primary_contact and insurance_contact. How can I do this?
Upvotes: 2
Views: 2102
Reputation: 2092
Don't know if this is the "best" way, but I got it to work by doing this:
$('#company').change(function () {
var company = $(this)[0].value.toString();
var primary_contact = $('#primary_contact').val();
var safety_contact = $('#safety_contact').val();
var insurance_contact = $('#insurance_contact').val();
$.getJSON('<%= ResolveUrl("~/Subcontracts/CompanyContacts/") %>' + company, null, function (data) {
$('.contact').empty().append("<option value=''>**Select Contact**</option>");
$.each(data, function (index, optionData) {
$('.contact').append("<option value='" + optionData.contact_id + "'>" + optionData.contact_name + "</option>");
});
$('#primary_contact').val(primary_contact);
$('#safety_contact').val(safety_contact);
$('#insurance_contact').val(insurance_contact);
});
});
Upvotes: 3
Reputation: 21388
Give this a try:
$('#company').change(function () {
var company = $(this)[0].value.toString();
for (var i=0; i<this.options.length; i++){
if (this.options[i].selected==true){
var contact = this.options[i].value.toString();
break;
}
}
$.getJSON('<%= ResolveUrl("~/Subcontracts/CompanyContacts/") %>' + company, null, function (data) {
$('.contact').empty().append("<option value=''>**Select Contact**</option>");
$.each(data, function (index, optionData) {
if (optionData.contact_id == contact)
$('.contact').append("<option value='" + optionData.contact_id + " selected='selected''>" + optionData.contact_name + "</option>");
else
$('.contact').append("<option value='" + optionData.contact_id + "'>" + optionData.contact_name + "</option>");
});
});
});
Upvotes: 0