Q:

Selecting an option based on the value of its data attribute

I want to choose (aka jQuery preselect) and set the value based on data variable. The list has 3 items having same values but differing data-d.
Suppose I have variable selectvar="d" then it should change to 2 item in the list.
<select id="select2">
    <option data-id="mo" value="1" style="display: none;">1</option>
    <option data-id="d" value="1" style="">one</option>
    <option data-id="h" value="1" style="display: none;">o-ne</option>
    <option data-id="mo" value="2" style="display: none;">2</option>
    <option data-id="d" value="2" style="">two</option>
    <option data-id="h" value="2" style="display: none;">t-wo</option>
    <option data-id="mo" value="3" style="display: none;">3</option>
    <option data-id="d" value="3" style="">three</option>
    <option data-id="h" value="3" style="display: none;">t-hree</option>
</select>

val = 2
selectvar="d"
$("#select2 option[data-id='d'][value='2']").prop("selected", true);

A:

Use below code and give id to your select.
$("#select2 option[data-id='" + selectvar + "']").prop("selected", true);

