如何使用JQuery通过选项列表索引号改变JQuery-select2下拉列表的选择值

How to change selected value of JQuery-select2 dropdown by option list Index number using JQuery

本文关键字:JQuery-select2 改变 下拉列表 选择 索引 JQuery 何使用 列表 选项      更新时间:2023-09-26

我使用下拉框,这是使用jquery -select版本3.5实现的。

我想用JQuery设置从列表中选择的第二个项目,如$("#fieldId").prop("selectedIndex",1)

有可能吗?

Thanks in advance

$('#fieldId').select2("val",$('#fieldId option:eq(1)').val());
/*By using eq(), the index number should be calculated from 0*/

$('#fieldId').select2("val",$('#fieldId option:nth-child(2)').val());
/*By using nth-child(), the index number should be calculated from 1*/

可能有用

如果你指的是select下拉菜单,那么这应该可以解决你的问题

<select>
    <option>1st item</option>
    <option selected>2nd item</option>
    <option>3rd item</option>
</select>

编辑:你可以这样做

$('select option:nth-child(2)').attr('selected', true);
$('#selectId').find('option').each(function(index,element){
    if(element.value.toLowerCase().trim() == 'VAL_TO_MATCH'){
         $("#selectId").prop('selectedIndex', index).change();
    }
});