Reputation: 12512
I have a selector with several options. There's also an element on the page with a numeric value in it. I need to add SELECTED attribute to the option that matches the value in the element.
var myVal = $(this).closest('.panel').find('.dist').text();
$(this).closest('.panel').find('.mySelector option[value='+myVal +']').prop('selected', 'selected');
<select class="mySelector">
<option>1
<option>2
<option>3
</select>
<span class="dist">3</span>
I think I'm missing something...
Upvotes: 0
Views: 50
Reputation: 14308
Your option tags are missing the value attribute and the closing tag.
I've modified your example slightly and added a button to demonstrate the solution.
$("#selectButton").click(function() {
var myVal = $(this).closest('.panel').find('.dist').text();
$(this).closest('.panel').find('.mySelector option[value='+myVal +']').prop('selected', 'selected');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="panel">
<select class="mySelector">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<span class="dist">3</span>
<input id="selectButton" type="button" value="select option" />
</div>
Upvotes: 1