Skip to content Skip to sidebar Skip to footer

How Do I Disable, Hide, Or Remove Selected Option In Other Selects With The Same Options?

I'm writing a form with 4 in the ot

Solution 1:

In your change event listener, you can get the current set of selected values from all <select> elements in the group, and then loop through each element's options to both disable the options currently selected elsewhere in the group as well as re-enable any options that were previously selected but have since been changed. You can avoid disabling the first "label" option in each of your selects by checking the value before disabling / enabling options.

You could use this same approach to hide or remove options keeping in mind that there are some browser compatibility issues when trying to hide <option> elements and that you would need some additional code to store the complete list of options if you were going to remove and restore them.

const selects = document.querySelectorAll('.select-group');
selects.forEach((elem) => {
  elem.addEventListener('change', (event) => {
    const values = Array.from(selects).map((select) => select.value);
    for (const select of selects) {
      select.querySelectorAll('option').forEach((option) => {
        const value = option.value;
        if (value &&  value !== select.value && values.includes(value)) {
          option.disabled = true;
        } else {
          option.disabled = false;
        }
      });
    }
  });
});
<selectclass="select-group"><optionvalue="">Select...</option><optionvalue="first">First Value</option><optionvalue="second">Second Value</option><optionvalue="third">Third Value</option></select><selectclass="select-group"><optionvalue="">Select...</option><optionvalue="first">First Value</option><optionvalue="second">Second Value</option><optionvalue="third">Third Value</option></select><selectclass="select-group"><optionvalue="">Select...</option><optionvalue="first">First Value</option><optionvalue="second">Second Value</option><optionvalue="third">Third Value</option></select>

Solution 2:

Thanks a lot for your help! I added a small 'if' to fix my bug and it works perfectly (until the next bug ^^):

if(value !== ""){
option.disabled = true;
}

Solution 3:

Or I could just :

if (value && value !== select.value && values.includes(value) && value !== "") {
option.disabled = true;            
} 

Another difficulty when you begin : learn to write simple code ^^z

Post a Comment for "How Do I Disable, Hide, Or Remove Selected Option In Other Selects With The Same Options?"