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>
2
Answers
Not so hard a learn…
This snippet does exactly what the OP is asking:
— setting the
selected
property totrue
on the correspondingoption
elements/, */
(comma followed by (zero or more) spaces