Ad Code

Add Items to ListBox with TextBox by using jQuery

In this article i'm going to explain about how to add textbox values to listbox by using jQuery. Let me explain with the simple example of adding Cities name from textbox to listbox by using jquery.

HTML Markup : Design

In WebForm1.aspx page add Textbox, Button and ListBox Control and in Source Code add jQuery file under header section with the tags of <script/>

<span id="spCity"></span>
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" />

<a href="#">Remove City<a> <asp:ListBox ID="listBoxCity" runat="server" CssClass="list-group" style="border:0px; overflow-y:hidden; height:83px; width:300px;">

jQuery : Add TextBox to Listbox

In below jQuery i'm applying a condition is, its allow upto 10 cities entries if you enter 11th city name it give error message. If you want to remove city from the listbox that which your added in the listbox, simply select which ever city you want to remove once you select city name from listbox their is a a anchor tags will hidden by default that enable and show as Remove City click it.

<script src="" async defer></script>
   var count = [];
   var i = 0;
   $("#btnAddAdd").click(function () {        
   var txt = $("#txtCity").val();
    if (jQuery.inArray(txt, count) != "-1") {
      $("#spCity").text('City alread exists');
   } else {
     var listCount = $('[id$=listBoxCity] option').length;
     if (listCount <= 10) {
      count[listCount] = txt;
      var alreadyExist = false;
      $('[id$=listBoxCity] option').each(function () {
       if ($(this).val() == txt) {
        $("#spCity").text('City alread exists');
        alreadyExist = true;
   if (!alreadyExist) {
   $('[id$=listBoxCity]').append($('<option></option>').attr('value', count[listCount]).text(txt));
 } else {
  $("#spCity").text('10 City limit exceed');

jQuery : Enable Remove City Button

By default this remove city button disable, and this button appears when user select listbox items.

//Remove Value from the List
        $('[id$=listBoxKeywords]').click(function (e) {        
            var $target = $(;
            if ($'option')) {

jQuery - Remove City Button Click

After selecting items from listbox just click on remove button to remove permanently from the listbox

$("#arkyw").click(function () {
            var a = $('[id$=listBoxKeywords] option:selected').val();
            var id = $('[id$=listBoxKeywords] option').length;
            //alert('ListCount : ' + a);
            //alert('Total List Item : ' + id);
            //alert('After Remove : ' + count[a-1]);
            count = jQuery.grep(count, function (e) {
                $('[id$=listBoxKeywords] option:selected').remove();
                return e != a;

Post a comment