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

前端 未结 21 1798
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:23

    For setting select value with triggering selected:

    $('select.opts').val('SEL1').change();
    

    For setting option from a scope:

    $('.selDiv option[value="SEL1"]')
        .attr('selected', 'selected')
        .change();
    

    This code use selector to find out the select object with condition, then change the selected attribute by attr().


    Futher, I recommend to add change() event after setting attribute to selected, by doing this the code will close to changing select by user.

提交回复
热议问题