Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery to add items in Listbox from Textbox

I am stuck somewhere using jquery to append the list box from a text box.

here is my jquery

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

I am using asp.net (c#) to develop my code

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

can someone please help as i am not able to get the values in list box.

like image 730
Pratik Avatar asked Jan 16 '23 04:01

Pratik


1 Answers

The jQuery selector $() is missing for "#<%=lstSvcName.ClientID %>" so you will get id of lstSvcName instead of object.

I also changed the append statement as it does not have correct syntax.

"#<%=lstSvcName.ClientID %>"

would be

$("#<%=lstSvcName.ClientID %>")

Your code will become

$("#<%= 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;
}); 

EDIT [ More functionality requested by OP for unique items in ListBox and clearing 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;
});
like image 57
Adil Avatar answered Jan 19 '23 00:01

Adil