Creating a table with items selected from a dropdown list

In this article we'll create a dropdown list, add each item selected into an array and display the contents of that array in a table using jQuery. We'll also be able to delete items from the array and table.

For anyone who has no idea what jQuery is, below is a brief explanation:

jQuery is a JavaScript Library that focuses on simplifying DOM manipulation, AJAX calls, and Event handling. It is used by JavaScript developers frequently.

jQuery uses a format, $(selector).action() to assign an element(s) to an event. To explain it in detail, $(selector) will call jQuery to select selector element(s), and assign it to an event API called .action().

Source: MDN Web Docs

Including jQuery in your web page can be as simple as pasting the integration code from the CDN like this:

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

The HTML

<div class="container">   

 <!-- The HTML dropdown list -->  
        <select id="items">
                <option>Apple </option>
                <option>Banana </option>
                <option>Onion </option>
                <option>Spinach </option>
                <option>Peach </option>
                <option>Carrot </option>
                <option>Grape </option>
        </select>


        <!-- This is just a paragraph with an empty span to display messages in later -->
        <p><span id="msg"></span></p>

        <!-- Selected items table -->
        <table id="table" border="1">

          <!-- Table header -->
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Item</th>
                        <th>Action</th>
                    </tr>
                </thead>
    
               <!-- Table body -->
                <tbody id="selectedItems">
    
                </tbody>
    
            </table>

    </div>

And the Javascript

<script type="text/javascript">

    //Create an empty array to store selected items
    var list = [];

    //Hide the table and messages span for now
    $('#table, #msg').hide();
    
    //When a user selects an item from the dropdown
    $( "#items" ).change(function() {   

        //$(this) is the select list and from it we find the option that has :selected. We store that in "item"
        var item = $(this).find(":selected").text();

        //Call the addToList function and pass the item to it
        addToList(item);

    });

    //The function receives the item when it get's called
    function addToList(item) {

        //indexOf(item) checks the list to see if the item exists. It it does not, the if statement will return -1
       if(list.indexOf(item) == -1) {

           //If the above returned -1 we add the item to the list
           list.push(item);

       }

       else {

           //If not -1, display a message for 2 seconds
           $('#msg').empty().show().text("Item already added to the list").delay(2000).fadeOut(500);
       }

       //Call the show rows function to display the contents of the list in the table body
        showRows();      

    }

    function showRows() {

         // Create an empty variable to store the rows in
         var selectedItems = '';

        //Loop through the items and add each item to the table as a row
        for (i = 0; i < list.length; i++) {

            //Create a number variable and give it a value of array key + 1
            var num = i + 1;

            //Add each item from the list array as a table row
            selectedItems += "<tr id='" + i + "'> <td>" + num + "</td> <td>" + list[i] + "</td> <td> <span id='remove'>Remove</span> </td></tr>";

            }  

            //Display the items rows stored in selected items in the table body
            $('#selectedItems').html(selectedItems);

            //Show table, which we hid earlier
            $('#table').show();
    }


       //Add a click event listener to the rows in the table and check if the span with id #remove was clicked
       $('#selectedItems').on('click', 'span#remove', function(){

        //The span is inside a <td> tag and the td is inside a <tr>. So it's 2 parents up. Get the id from the tr.
        var key = $(this).parent().parent()[0].id;

        //Remove the item that has the key stored in key variable
        list.splice(key,1);
        
        //Show updated rows
        showRows();

        //If that was the last item, hide the table
        if(list.length == 0) {
            $('#table').hide();
        }
                
       
    });
        
</script> 

Demo

No Item Action

Add new comment

The content of this field is kept private and will not be shown publicly.
Target Image