I have been trying to dynamically disable couple of options in a dynamically generated jQuery Select2 based on an option selected on another Select2. I have tried couple of suggestions out there, but couldn't succeed.
This one (how to let jquery select2 disable one option dynamically?) was the closest, but again, in my case I do not already have the <select>
with options written but is generated on-the-fly.
The value and text for options is pulled from a table and will change with time, so prefer to implement the current way (not as in the above link). If this is not at all possible then maybe {{templating}}
maybe the last resort. Example code below, I have also put a demo here: http://jsfiddle.net/s_j_l/gqbzh5y0/23/
HTML:
User Roles:
<div id="userr"></div>
Quarters:
<div id="qtr"></div>
JS:
$("#userr").select2({
data: _.map(userroles, function (json) {
return {
id: json.roleid,
text: json.role
}
}),
placeholder: 'Select User Role',
allowClear: true,
containerCssClass: 'select-block-level'
}).on('change', function (e) {
if (e.val == 'user') $("#qtr").find('option[value="2013Q4"]').attr('disabled', 'disabled');
});
$("#qtr").select2({
data: _.map(quarters, function (json) {
return {
id: json.qid,
text: json.quarter
}
}),
placeholder: 'Select Quarters',
allowClear: true,
containerCssClass: 'select-block-level'
}).on('change', function (e) {});
});
DATA:
{"userroles":[{"roleid":"admin","role":"Admin"},{"roleid":"user","role":"User"},{"roleid":"audit","role":"Audit"},{"roleid":"client","role":"Client"}],"quarters":[{"qid":"2014Q3","quarter":"2014 Q3"},{"qid":"2014Q2","quarter":"2014 Q2"},{"qid":"2014Q1","quarter":"2014 Q1"},{"qid":"2013Q4","quarter":"2013 Q4"},{"qid":"2013Q3","quarter":"2013 Q3"},{"qid":"2013Q2","quarter":"2013 Q2"},{"qid":"2013Q1","quarter":"2013 Q1"},{"qid":"2012Q4","quarter":"2012 Q4"},{"qid":"2012Q3","quarter":"2012 Q3"},{"qid":"2012Q2","quarter":"2012 Q2"},{"qid":"2012Q1","quarter":"2012 Q1"}]}