I had a requirement to conditionally disable a single dropdown option, based on the selection of two radio button fields. I was then required to create an alert to advise why that dropdown option was disabled (by using a mousedown select event). I'm sure it can be easily adapted to checkboxes, multiple select2 disables and the like. The difficulty was getting the alert to work as the select2 .prop('disabled', true); does exactly that - disables that element.
The code goes in hooks/yourtablename-dv.js
Code: Select all
$j(function() {
$j( document ).ready(function() {
$j('#yourfieldname').select2();
function checkRadio() {
if ($j('#yourradioID1').is(':checked') || $j('#yourradioID1').is(':checked')) {
$j('#yourfieldname option[value="Your Dropdown Option"]').prop('disabled', true);
} else {
$j('#yourfieldname option[value="Your Dropdown Option"]').prop('disabled', false);
}
$j('#yourfieldname').select2(); // Re-initialize select2 to reflect changes
}
$j('#yourfieldname').on('change', function() {
checkRadio();
});
checkRadio(); // Initial check
});
});
$j(function() {
$j(document).ready(function() {
$j('#yourfieldname').select2();
// Add event listener for Select2 yourfieldname event
$j('#yourfieldname').on('select2-yourfieldname', function() {
// Add click event listener to disabled options
$j('li.select2-disabled').each(function() {
if ($j(this).text() === 'Your Dropdown Option') {
$j(this).on('mousedown', function(event) {
alert('Your Dropdown Option is Disabled. You MUST select and SAVE an option for BOTH "Your Radio 1" and "Your Radio 2" to enable this option');
// Prevent the default action
event.preventDefault();
});
}
});
});
});
});