向Select动态添加元素,并在JQuery中设置selectindex

Dynamically adding element to Select and setting the selectindex in JQuery

本文关键字:JQuery 设置 selectindex 并在 Select 动态 添加 元素      更新时间:2023-09-26

我创建了一个动态选择列表框,如下所示

for (var i in c) {
            //alert(c[i].IsDefault);
            if(c[i].IsDefault==true){
                //alert('found default');
                $("#AnsType").append("<option value='" + c[i].ID + "'>" + c[i].Code+ "</option>");
                temp = c[i].Code;
            }
            else{
                $("#AnsType").append("<option value='" + c[i].ID + "'>" + c[i].Code+ "</option>");
            }
        }

刷新

$('#AnsType').selectmenu('refresh');

我尝试了所有这些方法,并试图在列表中选择第二个元素。对我不起作用

$('#AnsType').val(temp.toString());
$('#AnsType').get(3).selectedIndex = 3;
$('select#AnsType').val('3');
$("#AnsType option[text='3']").attr("selected","selected") ;
$("#mydropdownlist").attr('selectedIndex', 1);
$('#AnsType').val(3);
$("#AnsType").attr('selectedIndex', 2);
$("#AnsType").val(c[parseInt(temp)].Code);
$("select#AnsType option[selected]").removeAttr("selected");
$("select#AnsType option[value='"+temp+"']").attr("selected", "selected");

这就是当我的列表框创建时的方式

<select id="AnsType" name="AnsType">
        <option value="1">Obokad</option>
        <option value="3">Egen bokning</option>
</select>

感谢您的帮助。。

如果您希望在创建菜单时预先选择某个元素,请将selected属性添加到相应的选项元素:

if(c[i].IsDefault==true){
    $("#AnsType")
        .append("<option value='" + c[i].ID + " selected='selected'">" + c[i].Code+ "</option>");
    temp = c[i].Code;
}

请注意,在以编程方式更改底层select元素的值后,您必须再次刷新select菜单:

$('#AnsType').val('3');
$('#AnsType').selectmenu('refresh');

文档

刷新更新自定义选择
这用于更新自定义选择以反映本机选择元素的值。如果选择中的选项数与自定义菜单中的项目数不同,则会重新生成自定义菜单。此外,如果你通过了一个真正的论点,你可以强制重建