Search code examples
javascripthtmlcheckboxhtml-tableinnerhtml

how can i print a table of checkboxes using js?


in localStorage I have an array with products and I want to print checkboxes with the name of the products having the attribute nameRis equal to another nameRis I have in sessionStorage. My code looks like this:

   <table id="checkboxes_food"> </table>

    <script type="text/javascript">
        var x = [];
        x = JSON.parse(localStorage.getItem("spec_ris")); //products
        var y = JSON.parse(sessionStorage.getItem("loggedris")); //logged user 

        for (var i = 0; i < x.length; i++) {
            if (x[i].nameRis=== y.nameRis) {
                
                    document.getElementById('checkboxes_food').innerHTML = "<tr> <th><input type='Checkbox' name='food'>" + x[i].name+ "</th>";
             
            }
        }

    </script>

It works but it keeps overwrite the products, if I have two products from, for example, "Ciccio" this code shows me only the second one but I want it to show me both. How can I improve my code to do so? Thanks :)


Solution

  • The problem is that you are overriding the content inside the table. Try this:

    document.getElementById('checkboxes_food').innerHTML += "<tr> <th><input type='Checkbox' name='food'>" + x[i].name+ "</th>";
    

    Use += instead of =