How do you select a particular option in a SELECT element in jQuery?

前端 未结 21 1969
Happy的楠姐
Happy的楠姐 2020-11-22 10:55

If you know the Index, Value or Text. also if you don\'t have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

21条回答
  •  [愿得一人]
    2020-11-22 11:46

    A selector to get the middle option-element by value is

    $('.selDiv option[value="SEL1"]')
    

    For an index:

    $('.selDiv option:eq(1)')
    

    For a known text:

    $('.selDiv option:contains("Selection 1")')
    

    EDIT: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:

    $('.selDiv option:eq(1)').prop('selected', true)
    

    In older versions:

    $('.selDiv option:eq(1)').attr('selected', 'selected')
    

    EDIT2: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no selector to match the full text, but a filter works:

     $('.selDiv option')
        .filter(function(i, e) { return $(e).text() == "Selection 1"})
    

    EDIT3: Use caution with $(e).text() as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no tag):

    
    

    If you simply use e.text any extra whitespace like the trailing newline will be removed, making the comparison more robust.

提交回复
热议问题