Conditionally disable a select2 dropdown option based on radio/checkbox selection

Got something cool to share with AppGini users? Feel free to post it here!
Post Reply
peebee
AppGini Super Hero
AppGini Super Hero
Posts: 355
Joined: 2013-03-21 04:37

Conditionally disable a select2 dropdown option based on radio/checkbox selection

Post by peebee » 2024-05-23 00:59

Just thought I'd share this here in case anybody else has use for it, or something similar.

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();
                        });
                    }
                });
            });
        });
});

User avatar
a.gneady
Site Admin
Posts: 1309
Joined: 2012-09-27 14:46
Contact:

Re: Conditionally disable a select2 dropdown option based on radio/checkbox selection

Post by a.gneady » 2024-05-24 14:17

Thanks for sharing :)
:idea: AppGini plugins to add more power to your apps:

Post Reply