Search code examples
jquerydrop-down-menuselected

jQuery change selected using two attributes (e.g. class and value)


I have a <select> where options can have same value but with different class. Is it possible to change selected option based on those two elements together?

eg:

<select id="select">
  <option class="ABC" value="99">Option 1</option>
  <option class="DEF" value="99">Option 2</option>
  <option class="ABC" value="98">Option 3</option>
  <!-- ....... -->
</select>

if(var === null) {
  $('#select option[class="ABC" value="99"]').prop('selected', true);
}

This is what I tried, but doesn't work


Solution

  • Use two attribute selectors, not multiple attributes in one selector.

    $('#select option[class="ABC"][value="99"]').prop('selected', true);
    

    Also, the normal way to match a class is with .ABC, so this should be written as

    $('#select option.ABC[value="99"]').prop('selected', true);