Using Jquery to add items in Listbox from Textbox

16,782

Solution 1

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

Solution 2

Try something like this. This may help you. Change the return value for your convenience.

   $('#<%= btnAddSvc.ClientID %>').click(function () {
            $textbox = $('#<%= txtServiceName.ClientID %>');
            $listbox = $('#<%= lstSvcName.ClientID %>');
            $listbox.append($('<option></option>').attr('value', $textbox.val()).text($textbox.val()));
            return false;
        });

Solution 3

You could do it using jquery manipulating the DOM but... Now there's a more elegant way to do it: an object-oriented way (using a MVVM - Model View ViewModel), using knockoutjs

Knockoutjs Nuget Package

You create a binding to your list just adding data-bind="options: elements" to your list, and you are always working with objects, never with DOM elements, in this example I have a string array but you can create custom objects and bind them using just a little variation in the syntax

The way to do it is:

<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="Scripts/knockout-2.1.0.js"></script>
<script type="text/javascript">
    $(function () {
        var model = {
            elements: ko.observableArray(),
            addElement: function () {
                this.elements.push($("#<%= this.newElement.ClientID %>").val());
            }
        };

        ko.applyBindings(model);
    });
</script>


    <asp:ListBox runat="server" ID="myListbox" Rows="10" Width="25%" data-bind="options: elements">
    </asp:ListBox>
    <br />
    <asp:TextBox runat="server" ID="newElement"></asp:TextBox>
    <input type="button" id="addElement" value="Add element" data-bind="click: addElement" />

This is the output:

enter image description here

Share:
16,782
Pratik
Author by

Pratik

From more than 8+ years I have been working on Microsoft.Net technologies. I am glad to be a part of Stack community and love the enthusiasm of people here. “If it was easy, everybody would be doing it.”

Updated on June 15, 2022

Comments

  • Pratik
    Pratik almost 2 years

    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.

  • Adil
    Adil almost 12 years
    Try it now, you had wrong syntax for adding item in listbox, check it now
  • Pratik
    Pratik almost 12 years
    Surprisigly this is also not working :( why you have included 5</option> what 5 means here
  • Adil
    Adil almost 12 years
    It was typing mistake and I have already removed it, let me check why its not working
  • Adil
    Adil almost 12 years
    Its working, I do not know why not working on your side. Have you included jquery file? and placed this script at right place. Do some debugging it should work. Also take latest code from answer you may not have latest.
  • Adil
    Adil almost 12 years
    Here is my answer for debugging javascript that may help you stackoverflow.com/questions/10573819/…
  • Pratik
    Pratik almost 12 years
    This is great thanks for your help : One more help needed how can i avoid the duplicates and also delete the ones on delete keystroke
  • Pratik
    Pratik almost 12 years
    Thanks a lot adil for your help i think i might have missed something but same code from raaghav started working for me :)
  • Adil
    Adil almost 12 years
    Your are welcome, I found what was missing on your side, give it a try now and get updated code from answer.
  • Pratik
    Pratik almost 12 years
    Yes its working now :) I am newbie to the world of jquery srry for the trobuble but can i ask ur help in promting user that value already exist i selection list and also clear the text box
  • Pratik
    Pratik almost 12 years
  • Raaghav
    Raaghav almost 12 years
    Sorry for the delay. I dint come online these days. @PratikGupta , Try something like this to delete $('#<%= btnDelete.ClientID %>').click(function() { $listBox = $('#<%= lstBox.ClientID %>'); $selectedItem = $listBox.find('option:selected'); $selectedItem.remove(); return false; });
  • Raaghav
    Raaghav almost 12 years
    @PratikGupta , Just try these lines of code to check for duplicate entries. I'm not sure this will work. Try modify some lines and try. $textbox = $('#<%= txtText.ClientID %>'); for (var i = 0, j = selectObject.options.length; i < j; i++) { if(selectObject.options[i].value==$textbox.val()) { alert('This Item already exists'); e.preventDefault(); } }