开发者

How to use JQuery to select the nth option

I have the following HTML

<select onchange="this.form.submit()" name="name">
    <option value="9995101E01#17201044055P开发者_如何学GoM">9995101E01#17201044055PM</option>
    <option value="GRR-Example">GRR-Example</option>
    <option value="admin">admin</option>
    <option value="123w">123w</option>
</select>

May I know how I can use JQuery to option with value "admin"?


$('select[name=name] option:eq(2)').attr('selected', 'selected');

Demo.


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.


I think the nth-child pseudo-class is what you're looking for:

$('select option:nth-child(3)').attr('selected', 'selected');


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


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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜