I have two select fields in my form. The first one is single-select and the other is multiple-select. Now what I want to do is select options in the multiple-select with given data depending on the chosen option in the single-select. To do this I'm firing an ajax-request when the single-select is changed:
$.ajax({
type : 'POST',
url : '/Controller/getMultipleSelectIds',
data : {
singleSelectId: singleSelectId
},
success : function(data) {
var multipleSelectIds= JSON.parse(data);
$("#multipleSelectFieldId option:selected").prop("selected", false);
$("#multipleSelectFieldId option").each(function()
{
if ($(this).val() in multipleSelectIds) {
$(this).attr('selected','selected');
}
});
$("#multipleSelectFieldId").trigger("chosen:updated");
}
});
Lets say I have values like these in the database for the single-select-Ids:
array(
"ssId1" => array(1,2,4,5),
"ssId2" => array(1,3,5)
)
Now I choose the first entry in the single-select ("ssId1") and everything works fine, meaning the multiple-select gets filled just like it should (with the options with the given values 1,2,4 and 5). But when I change the single-select again to another option ("ssId2") the chosen-select only shows me option 3 (which is one value that is not one of "ssId1"). This continues until I have no more options in the chosen multiple-select.
I've checked and the options in the hidden multiple-select field are set correctly. So now the question is: Is this a bug in the chosen plugin or am I doing something wrong?
EDIT
Tried to find the problem and for this made the source select visible. It seems that there is a problem with removeAttr
or .prop("selected", false)
or maybe even .attr('selected','selected'). When I switch between the two choices of the single-select only the option 3 is marked (blue background) but all 3 options have the selected property in the html code. I've a similar problem when I tried to select all options in a multiple-select (required) field via js/jquery in IE 11 and submitting the form IE said that there is no option chosen. What am I doing wrong?