Search code examples
jquery

How to disable options with especific value in all selects with same name?


I have several selects like this:

<select id="slctDat1" name="slctDat1" class="form-select">
      <option value="1">Text1</option>
</select>

<select id="slctDat2" name="slctDat2" class="form-select">
      <option value="1">Text1</option>
</select>

I know how to select them all with

$('select[name="slctDat[]"]')

What I need the program to do is to get the selected value of the select 'onchange' and disabled that value on all of them so it would look something like this:

<select id="slctDat1" name="slctDat1" class="form-select">
      <option value="1" selected disabled>Text1</option>
</select>

<select id="slctDat2" name="slctDat2" class="form-select">
      <option value="1" disabled>Text1</option>
</select>

Solution

  • I noticed that the SELECT on the snippet you provided have the same class. I imagine this is true for the rest.

    With this in mind, you could have something like this:

    $(document).ready(function() {
        /*
         * Function to disable selected value 
         * in all selects with class 'form-select'
         */
        function disableSelectedValue() {
            /*
             * Get the selected value
             */
            var selectedValue = $(this).val();
            
            /*
             * Disable the option with the 
             * selected value in all selects 
             * with the same class
             */
            $('.form-select option').each(function() {
                if ($(this).val() === selectedValue) {
                    /*
                     * Disable the option
                     */
                    $(this).attr('disabled', 'disabled');
                } else {
                    /*
                     * Ensure other options are enabled
                     */
                    $(this).removeAttr('disabled'); 
                }
            });
        }
    
        /*
         * Attach the function to the change 
         * event of all selects with the class 
         * 'form-select'
         */
        $('.form-select').on('change', disableSelectedValue);
    });
    

    I imagine that this is what you had in mind.