idlackage idlackage - 3 months ago 8
Javascript Question

Select the first option by value when there are duplicate values

I have a

select
list that contains duplicate values. I don't have the power to change this.

<select id="dropdown">
<option value="1">Item 1</option>
<option value="1">Item 1 again under a different name</option>
<option value="2">Item 2</option>
</select>


In a different place, I have a link element that, when clicked, calls
$("#dropdown").val(1)
. This "Item 1 again under a different name" to be selected and displayed. I want "Item 1" to be selected instead. How can I accomplish this?

Answer

To do that you can select the option element by the value attribute and use the :first selector. Try this:

var value = 1;
$('#dropdown option[value="' + value + '"]:first').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
  <option>Please select...</option>
  <option value="1">Item 1</option>
  <option value="1">Item 1 again under a different name</option>
  <option value="2">Item 2</option>
</select>

Comments