简体   繁体   中英

Dropdown item insert between two list items using javascript

I have radio button and dropdown like this:

Dropdown

 <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>

Radio button

<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>

script :

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
}

}

My question is , how to insert a new list item between two items using javascript ..

You can use like this

You need to find the index and then use as follows

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

In your case

Find the index first as follows

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

then delete and then add at the above index

I have put the below script in else block, it's work fine..

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM