samedi 23 mars 2019

How to print a table made in JavaScript with the data filtered by checkboxes, without using jQuery?

I have a table displaying some data, made only in JavaScript. Now, I put some checkboxes in order to filter the the data and show the table with the matches selected before. Without using jQuery, and without "hidding" the rows unselected, I need to create a new table every time a checkbox is selected.

This is the HTML

<form action="/action_page.php">
            <input type="checkbox" name="sParty" value="democrat"> Democrat
            <input type="checkbox" name="sParty" value="republican"> Republican
            <input type="checkbox" name="sParty" value="independent" checked> Independent
            <input type="submit" value="Submit">
        </form>
    </div>
    <div class="row" id="tablerow">
        <div class="col">
        <table class="table table-hover table-sm" id="sendata">
        </table></div>
    </div>
    </div></div>

And this the JS (I started by getting the NodeList from the checkboxes)

var memberArr=data.results[0].members;  //BRINGS DATA FROM JSON FILA
            var newArr = [];                                
            for (var i = 0; i < memberArr.length; i++) {
                var obj = new Object; 
                obj.fullName= memberArr[i].first_name + " " + (memberArr[i].middle_name || " ") +  " " + memberArr[i].last_name;                    
                obj.party = memberArr[i].party;
                obj.state = memberArr[i].state;
                obj.seniority = memberArr[i].seniority;
                obj.votes_with_party_pct=memberArr[i].votes_with_party_pct + "  %" ;
                obj.nameLink=memberArr[i].url;
                newArr.push(obj);                           
            } //newArr is the array with all members(objects)

      var checkedBoxes = 
      document.querySelectorAll('input[name=mycheckboxes]:checked');  //GET 
VALUE OF CHECKED CHECKBOXES





            var headersSenate={
                HfullName:"Full Name",
                Party:"Party Affilication",
                State:"State",
                Senior:"Seniority",
                Votes:"Votes w/Party (pct)",

            }
            var datos="<tr><th>" + headersSenate.HfullName + "</th><th>"+ headersSenate.Party + "</th><th>" + headersSenate.State+ "</th><th>"
            +headersSenate.Senior+ "</th><th>"+headersSenate.Votes+"</th>";

            for(var i=0; i<newArr.length; i++){
                datos+="<tr><td><a target='_blank' href=" + newArr[i].nameLink + ">"+ newArr[i].fullName + "</a></td><td>" + newArr[i].party
                 + "</td><td>" + newArr[i].state + "</td><td>" + newArr[i].seniority + "</td><td>" + newArr[i].votes_with_party_pct + "</td>";
            }
            document.getElementById("sendata").innerHTML= datos;




Aucun commentaire:

Enregistrer un commentaire