How to use JQuery to select the nth option

后端 未结 6 991
借酒劲吻你
借酒劲吻你 2021-02-05 01:15

I have the following HTML


                        
    
提交评论

  • 2021-02-05 01:28

    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

    0 讨论(0)
  • 2021-02-05 01:36

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

    $('select option:nth-child(3)').attr('selected', 'selected');
    
    0 讨论(0)
  • 2021-02-05 01:38

    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.

    0 讨论(0)
  • 2021-02-05 01:42

    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());
    
    0 讨论(0)
  • 2021-02-05 01:52

    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 讨论(0)
  • 提交回复
    热议问题