从下拉选定项目向列表框添加值

时间:2014-06-18 20:40:36

标签: asp.net

代码来自usercontrol

 <asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem>Maer</asp:ListItem>
<asp:ListItem>Cor</asp:ListItem>


   

<asp:Button ID="btn1" runat="server" Style="font-size: small; width: 70px; font-weight:    lighter" Text="Add" OnClick="btn1_click" />

 <asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple" Width="220px">                       </asp:ListBox>

javascript功能

function btn1_click()
 {

如何从下拉列表中获取值并添加到列表框?

2 个答案:

答案 0 :(得分:0)

以下是如何添加当前选定的DropDownList2项并使用JavaScript将其添加到ListBox2的方法。单击Btn1后,在客户端/浏览器端执行此代码:

<强> JavaScript的:

function btn1_click() {
    var mylistRef = document.getElementById('<%= ListBox2.ClientID %>');

    var selectedItemValue = document.getElementById('<%= DropDownList2.ClientID %>').options[document.getElementById('<%= DropDownList2.ClientID %>').selectedIndex].value;
    var selectedItemText = document.getElementById('<%= DropDownList2.ClientID %>').options[document.getElementById('<%= DropDownList2.ClientID %>').selectedIndex].text;

    var option = document.createElement("option");
    option.text = selectedItemText;
    option.value = selectedItemValue;
    option.innerText = selectedItemText;
    mylistRef.options.add(option);
}

<强> ASPX:

<asp:DropDownList ID="DropDownList2" runat="server">
    <asp:ListItem value="1">Maer</asp:ListItem>
    <asp:ListItem value="2">Cor</asp:ListItem>
</asp:DropDownList>

<asp:Button ID="btn1" runat="server" Text="Add" OnClientClick="btn1_click()" />

<asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple" Width="220px" />

答案 1 :(得分:0)

$("#btn1").click(function (event) {

    var $ddl = $("#MC_ucOperations_DropDownList2"); Getting the id of the dropdown
    var $list = $("#MC_ucOperations_ListBox2"); // Getting the id of the listbox 

    var selValue = $ddl.val();
    var selText = $ddl.find("option:selected").text();

    var $opt = $("<option></option>");
    $opt.html(selText);
    $opt.attr("value", selValue);

    $list.append($opt);
});
相关问题