I have the following HTML
$('select[name=name] option:eq(2)').attr('selected', 'selected');
Demo.
I'd not advice setting value of select by using .attr('selected', 'selected')
.
It's bad practice. If two options have 'selected' attribute - then what is the value of select?
Here is the simple and easy version that will work:
$('select[name="name"]').val('admin');
DEMO
I think the nth-child
pseudo-class is what you're looking for:
$('select option:nth-child(3)').attr('selected', 'selected');
Like this:
$("select[name='name'] option:eq(2)").attr("selected", "selected");
EDIT:
To do what you want in your new edit, that is, select the option that has the value of admin
:
$("select[name='name'] option:contains('admin')").attr("selected", "selected");
See it working.
Just updating in case it helps someone. I had a similar requirement but in my case the dropdown was stored as a JavaScript variable. Also I liked how Denis Matafonov suggested to make the option in question selected. So here's the final block of code:
var target_dd = $('select[name=name]');
$(target_dd).val($(target_dd).find('option:eq(2)').html());
If you want to select nth option and trigger onchange event then:
function selectOption(nr) {
var select = $("select");
if (select.children().length >= nr) {
let value = select.find('option:eq(' + nr + ')').val();
select.val(value).change();
}
}