Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare variable and check if it contains select option

I have variable and two selects on a page. I would like to check if variable contains any of the select options, if it does, I want to set it to selected true.

In this example, dropdown 1 option ‘Webinar’ and dropdown 2 option ‘Transport Management’ should be selected true.

var query = "Webinar, Transport Management";

    $('select.select-dropdown option').each(function() {
        if (query.contains($(this).val())) {
            $(this).attr('selected', true);
        }
    });
<div class="dropdowns-group">
  <div class="dropdown">
    <label for="test">Test</label>
    <select class="select-dropdown" name="test" id="test">
      <option value="">Show all</option>
      <option value="Webinar">Webinar</option>
      <option value="Lecture">Lecture</option>
    </select>
  </div>

  <div class="dropdown">
    <label for="test2">Test2</label>
    <select class="select-dropdown" name="test2" id="test2">
      <option value="">Show all</option>
      <option value="Transport Management">Transport Management</option>
      <option value="Teaching">Teaching</option>

    </select>
  </div>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const preselectTest = (query) => {
  const queryArr = query.split(/, */);
  const elsSelect = document.querySelectorAll("#test, #test2");
  elsSelect.forEach(elSelect => {
    const elsOptions = elSelect.querySelectorAll("option");
    const opt = [...elsOptions].find(elOpt => queryArr.includes(elOpt.value) );
    if (opt) elSelect.value = opt.value;
  });
};

const query = "Webinar, Transport Management";
preselectTest(query);
<div class="dropdown">
  <label for="test">Test</label>
  <select class="select-dropdown" name="test" id="test">
    <option value="">Show all</option>
    <option value="Webinar">Webinar</option>
    <option value="Lecture">Lecture</option>
  </select>
</div>

<div class="dropdown">
  <label for="test2">Test2</label>
  <select class="select-dropdown" name="test2" id="test2">
    <option value="">Show all</option>
    <option value="Foo Bar">Foo Bar</option>
    <option value="Transport Management">Transport Management</option>
    <option value="Teaching">Teaching</option>
  </select>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading