Jacob
Jacob

Reputation: 15

How to allow the selection ONLY one option for certain values in a multiple selection dropdown list?

I want to make a dropdown menu with the following options. I want be able to select a select multiple value for option A, B, and C, but disable multiple selection if option D is selected. How can I do that? Thanks.

<label>Choose an option:</label>
  <select required multiple>
    <option>Please select</option>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">C</option>
  </select>

Upvotes: 0

Views: 1365

Answers (2)

Elias Glyptis
Elias Glyptis

Reputation: 530

let arr = [];
document.querySelector('#product_attr_ids').onchange = function(e) {
  if (this.querySelectorAll('option:checked').length <= 1) {
      arr = Array.apply(null, this.querySelectorAll('option:checked'));
  } else {
    Array.apply(null, this.querySelectorAll('option')).forEach(function(e) {
        e.selected = arr.indexOf(e) > -1;
    });
  }
}
<p>The html of selections with multiple set to true.</p>
<p>Pressing command + click will not allow you to choose more than one option</p>

<p>Javascript. You can chnage the <strong>('option:checked').length <= 1) </strong> to whatever number you want, peraps you want your users to choose only 2 or 3 options.</p>

<label>Choose an option:</label>
<br />
<select id="product_attr_ids" required multiple>
  <!-- Prevent user from select first blank option -->
  <option disabled>Please select</option>
  
  <option value="A">Attribute 1</option>
  <option value="B">Attribute 2</option>
  <option value="C">Attribute 3</option>
  <option value="D">Attribute 4</option>
  
</select>

Upvotes: 0

KooiInc
KooiInc

Reputation: 122898

Remove the other selected options if "D" is selected, otherwise allow multiple select (do nothing).

document.addEventListener("mouseup", checkMultiple);

function checkMultiple(evt) {
  const selectr = evt.target.closest(`select`);

  if (selectr && selectr.querySelector(`[value='D']:checked`)) {
      [...selectr.options].forEach(v => v.selected = v.value === `D`);
  }
}

/*
 Note: the above is a shortened version of
 the function in the original answer:
 
  function checkMultiple(evt) {
    if (!/option/i.test(evt.target.nodeName)) {
      return true;
    }
    const selector = evt.target.parentNode;
    const options = [...selector.querySelectorAll("option")];

    if (options.find(v => v.value === "D").selected) {
      options
        .filter(v => v.value !== "D")
        .forEach(v => v.selected = false);
    }
  }
*/
<label>Choose an option:</label>
<select required multiple>
  <option>Please select</option>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
  <option value="D">D</option>
</select>

Upvotes: 1

Related Questions