使用Jquery从Textbox中添加Listbox中的项目

Pra*_*tik 4 javascript c# asp.net jquery

我被卡在某处使用jquery从文本框中追加列表框.

这是我的jquery

  $("#btnAddSvc").click(function () {
        var svc = $("#<%= txtServiceName.ClientID %>").val();  //Its Let you know the textbox's value   
        svc.appendTo("#<%=lstSvcName.ClientID %>");
    }); 
Run Code Online (Sandbox Code Playgroud)

我正在使用asp.net(c#)来开发我的代码

<asp:Button ID="btnAddSvc" runat="server" Text=">>" Font-Size="Medium" />
<asp:ListBox ID="lstSvcName" runat="server" SelectionMode="Multiple" ToolTip="Selected Service Names"
                Width="169px"></asp:ListBox>
Run Code Online (Sandbox Code Playgroud)

有人可以请帮助,因为我无法获得列表框中的值.

Adi*_*dil 7

缺少jQuery选择器$(),"#<%=lstSvcName.ClientID %>"因此您将得到idlstSvcName而不是object.

我还更改了append语句,因为它没有正确的语法.

"#<%=lstSvcName.ClientID %>"
Run Code Online (Sandbox Code Playgroud)

将会

$("#<%=lstSvcName.ClientID %>")
Run Code Online (Sandbox Code Playgroud)

你的代码将成为

$("#<%= btnAddSvc.ClientID %>").click(function () {
      var svc = $("#<%= txtServiceName.ClientID %>").val();  //Its Let you know the textbox's value   
      $("#<%=lstSvcName.ClientID %>").append('<option value="'+svc+'">item '+svc+'</option>');
      return false;
}); 
Run Code Online (Sandbox Code Playgroud)

编辑[OP请求ListBox中的唯一项目和清除TextBox的更多功能]

$("#<%= btnAddSvc.ClientID %>").click(function () {
    var txt = $("#<%= txtServiceName.ClientID %>");
    var svc = $(txt).val();  //Its Let you know the textbox's value   
    var lst = $("#<%=lstSvcName.ClientID %>");
    var options = $("#<%=lstSvcName.ClientID %> option");
    var alreadyExist = false;
    $(options).each(function () {
        if ($(this).val() == svc) {
            alert("Item alread exists");
            alreadyExist = true;
            return;
        }
        txt.val("");
        // alert($(this).val());
    });
    if(!alreadyExist)
            $(lst).append('<option value="' + svc + '">' + svc + '</option>');
    return false;
});
Run Code Online (Sandbox Code Playgroud)