使用 javascript 在两个列表项之间插入下拉项

Dropdown item insert between two list items using javascript

本文关键字:列表 之间 插入 两个 javascript 使用      更新时间:2023-09-26

我有这样的单选按钮和下拉列表:

下拉列表

 <asp:RadioButtonList ID="rblTravelType" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" EnableViewState="false" onclick="TypeOfTravelOnChange('rblTypeOfTravel');">
        <asp:ListItem Value="A" Text="Air Travel"></asp:ListItem>
            <asp:ListItem Value="O" Text="Other Travel"></asp:ListItem>
    </asp:RadioButtonList>

单选按钮

<select name="DrTravelMode" id="DrTravelMode">
    <option value="">--Select--</option>
    <option value="A">Air</option>
    <option value="T">Bus</option>
    <option value="B">train</option>
<select>

脚本:

function TypeOfTravelOnChange(RadioButtonId) {
if ($('input:radio[name=' + RadioButtonId + ']:checked').val() == 'O') {
 $("#DrTravelMode option[value='A']").remove(); 
}
else
{
 // here i want to append the dropdown value "Air" between --Select-- and Bus
}

}

我的问题是,如何使用javascript在两个项目之间插入一个新的列表项。

你可以这样使用

您需要找到索引,然后按如下方式使用

$("select option").eq(index).before($("<option></option>").val(val).html(text));

在您的情况下

首先查找索引,如下所示

var index= $("#DrTravelMode option[value='A']").index()

然后删除,然后在上面的索引中添加

我已经将以下脚本放在else块中,它工作正常。

var select = document.getElementById("DrTravelMode");
    if ($("#DrTravelMode option[value='A']").length == 0) {
        var opt2 = document.createElement("option");
        opt2.text = "Air";
        opt2.value = "A";
        select.add(opt2, 1);
    }