Search code examples
jqueryhtmlcssmaterialize

How to make tags appear dynamically on a web page?


How to get the content of a selected checkbox and display it as a tag? (as displayed in E-commerce websites when a filter is selected)

I want to display the selected checkbox as a tag (Ex. Materialize CSS Chips)


Solution

  • To display the tags, add div element and give an id to the element to refer it later:

    <div id="chip_displayed"></div>
    

    Now, when a checkbox is selected, call the function to read the selected value.

    $(document.body).on('change', 'input[type="checkbox"]', function(){
        display();
    });
    

    display() will read the 'id' of the selected values and get 'name' parameter and add that to the Materialize CSS to display as a tag.

    function display()
    {
        document.getElementById("chip_displayed").innerHTML = "";
    
        var checked_ids = $('input:checkbox').filter(":checked").map(function () {
            return this.id;
        }).get();
    
        for(var i=0; checked_ids[i] ;i++)
        {
            var name = $('#'+checked_ids[i]).attr('name');
            document.getElementById("chip_displayed").innerHTML += "<div class='chip teal lighten-3' id='chip1'>"+name+"<i class='material-icons chip_close' id='close_chip1'>close</i></div>";
        }
    }