admin管理员组

文章数量:1323330

I'm dynamically creating a table using an HTML table and JavaScript Functions attatched to button clicks. I now want to take the data and store it into multidimensional array (if possible) using another button named finished. I'm having trouble even getting started with the last method to save it into array. I can't figure out how to retrieve the text data.

Here is my current HTML code.

<head>
    <title>TableTest</title>
    <script src="/javascript/func.js"></script>
</head>
<body>
      <form>
         <div id="Input">
                        <INPUT class="form-button" id="AddRow" type="button" value="Add Row" onclick="addRow('dataTable')" />
                        <INPUT class="form-button" id="DeleteRow" type="button" value="Delete Row(s)" onclick="deleteRow('dataTable')" />
                        <INPUT class="form-button" id="Finished" type="button" value="Finished" onclick="gatherData('dataTable')" />
                    <table id="dataTable" border="1" style="width:200px" id="mytable" align="center" cellspacing="3" cellpadding="4">       
                        <th>Select</th>
                        <th>Text1</th>
                        <th>Text2</th> 
                        <th>Text3</th>
                            <tr>
                            <td><INPUT type="checkbox" name="chk"/></td>
                            <td><INPUT type="text" name="text1"/></td>
                            <td><INPUT type="text" name="txt2"/></td>
                            <td><INPUT type="text" name="txt3"/></td>
                            </tr>
                    </table>    
            </div>
       </form>
</body>

Here is my JavaScript file:

 function addRow(tableID) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var colCount = table.rows[0].cells.length;

        for(var i=0; i<colCount; i++) {

            var newcell = row.insertCell(i);

            newcell.innerHTML = table.rows[1].cells[i].innerHTML;
            //alert(newcell.childNodes);
            switch(newcell.childNodes[0].type) {
                case "text":
                        newcell.childNodes[0].value = "";
                        break;
                case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
            }
        }
    }

    function deleteRow(tableID) {
        try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;

        for(var i=0; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked) {
                if(rowCount <= 2) {
                    alert("Cannot delete all the rows.");
                    break;
                }
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
        }catch(e) {
            alert(e);
        }
    }

function gatherData(){ 


 //Tests
        var table = document.getElementById('dataTable');
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;

        alert(rowCount);
        alert(row);
        alert(colCount); 
}

I'm dynamically creating a table using an HTML table and JavaScript Functions attatched to button clicks. I now want to take the data and store it into multidimensional array (if possible) using another button named finished. I'm having trouble even getting started with the last method to save it into array. I can't figure out how to retrieve the text data.

Here is my current HTML code.

<head>
    <title>TableTest</title>
    <script src="/javascript/func.js"></script>
</head>
<body>
      <form>
         <div id="Input">
                        <INPUT class="form-button" id="AddRow" type="button" value="Add Row" onclick="addRow('dataTable')" />
                        <INPUT class="form-button" id="DeleteRow" type="button" value="Delete Row(s)" onclick="deleteRow('dataTable')" />
                        <INPUT class="form-button" id="Finished" type="button" value="Finished" onclick="gatherData('dataTable')" />
                    <table id="dataTable" border="1" style="width:200px" id="mytable" align="center" cellspacing="3" cellpadding="4">       
                        <th>Select</th>
                        <th>Text1</th>
                        <th>Text2</th> 
                        <th>Text3</th>
                            <tr>
                            <td><INPUT type="checkbox" name="chk"/></td>
                            <td><INPUT type="text" name="text1"/></td>
                            <td><INPUT type="text" name="txt2"/></td>
                            <td><INPUT type="text" name="txt3"/></td>
                            </tr>
                    </table>    
            </div>
       </form>
</body>

Here is my JavaScript file:

 function addRow(tableID) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var colCount = table.rows[0].cells.length;

        for(var i=0; i<colCount; i++) {

            var newcell = row.insertCell(i);

            newcell.innerHTML = table.rows[1].cells[i].innerHTML;
            //alert(newcell.childNodes);
            switch(newcell.childNodes[0].type) {
                case "text":
                        newcell.childNodes[0].value = "";
                        break;
                case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
            }
        }
    }

    function deleteRow(tableID) {
        try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;

        for(var i=0; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked) {
                if(rowCount <= 2) {
                    alert("Cannot delete all the rows.");
                    break;
                }
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
        }catch(e) {
            alert(e);
        }
    }

function gatherData(){ 


 //Tests
        var table = document.getElementById('dataTable');
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;

        alert(rowCount);
        alert(row);
        alert(colCount); 
}
Share edited Oct 15, 2016 at 15:05 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 17, 2014 at 5:23 user2461876user2461876 391 gold badge1 silver badge10 bronze badges 1
  • To gather data, you don't want to insert new rows, just iterate over the rows that are there (like in the deleteRow function) and then for each cell, collect an appropriate value (say textConent or innerText, or form control value if checked, etc.). – RobG Commented Mar 17, 2014 at 6:01
Add a ment  | 

3 Answers 3

Reset to default 2

I reworked TameBadger's answer to build the array by row instead of by column. I also added a check to see if the given cell has a value before referencing it. In my case, not all cells have values.

 var table = document.getElementById('mainTable');

 if (table === null)
     return;

 if (table.rows[0].cells.length <= 1)
     return;

 var tblData = [];

 //Put a RowNumber name and values placeholder for the number of rows we have.
 for (r = 0; r < table.rows.length; r++) 
 {
     //Debug
     //console.log(" row: ", r);     

     tblData.push({
         name: "RowNumber" + r,
         items: []
     });

     //Get the cells for this row.
     var cells = table.rows[r].cells;

     //Loop through each column for this row and push the value...
     for (c = 0; c < cells.length; c++) 
     {
         var inputElem = cells[c].children[0];
         var tmpInputElem;

         if (inputElem == null)
         {
            tmpInputElem = "";
         }
         else
         {
            tmpInputElem = inputElem.value           
         }

         //Debug
         //console.log(" row-cel: ", r, "-", c, " ", inputElem);

         tblData[r].items.push(
         {
             //Comment out the type for now...
             //inputType: inputElem.getAttribute('type'),
             inputValue: tmpInputElem
         });
     }
 }

 //Debug
 //printData(tblData);

I tried to keep it simple, and also jQuery clean, so to speak.

    var data = [];
    function gatherData() {
         var table = document.getElementById('dataTable');
         for (r = 1; r < table.rows.length; r++) {

             var row = table.rows[r];
             var cells = row.cells;

             for (c = 0; c < cells.length; c++) {
                 var cell = cells[c];
                 var inputElem = cell.children[0];
                 var isInput = inputElem instanceof HTMLInputElement;
                 if (!isInput)
                     return;

                 var value = inputElem.value;

                 var isCheckbox = inputElem.getAttribute('type') == 'checkbox';
                 if (isCheckbox)
                     value = inputElem.checked;

                 var rowData = {};
                 rowData.inputType = inputElem.getAttribute('type');
                 rowData.inputValue = value;
                 data.push(rowData);
             }
         }
     }

     function startExec() {
         gatherData();
         for (i = 0; i < data.length; i++) {
             console.log(data[i].inputType);
             console.log(data[i].inputValue);
         }
     }
     //just wait for the dom to load, and then execute the function for testing
     document.addEventListener("DOMContentLoaded", startExec, false);

2nd Revision

 function getData() {

     var table = document.getElementById('dataTable');
     if (table === null)
         return;

     if (table.rows[0].cells.length <= 1)
         return;

     var data = [];
     for (l = 0; l < table.rows[0].cells.length; l++) {
         data.push({
             items: [],
             name: "ColumnNumber" + l
         });
     }

     for (i = 1; i < table.rows.length; i++) {
         var cells = table.rows[i].cells;
         for (c = 0; c < cells.length; c++) {
             var inputElem = cells[c].children[0];
             data[c].items.push({
                 inputType: inputElem.getAttribute('type'),
                 inputValue: inputElem.value
             });
         }
     }
     printData(data);
 }

 function printData(data) {
     for (i = 0; i < data.length; i++) {
         for (k = 0; k < data[i].items.length; k++) {
             console.log(data[i].items[k].inputValue);
         }
     }
 }

 document.addEventListener("DOMContentLoaded", getData(), false);

It's great that you're starting off and doing the table manipulation yourself, and I would remend continuing that, if you want to peak into a bigger codebase I would remend checking out jTable's. Even though it's a jQuery plugin, you'll still be able to learn something from looking at the code structure for handling all the logic surrounding building a table according to a dataset and adding records etc.

Is this what you are looking for?

JSFIDDLE

$(document).ready(function(){
    $('#Finished').click(function(){
        var my_arr=[];

        $('td').each(function(){

            if ($(this).children().is(':checkbox') )
            {
                if($(this).children().prop('checked'))
                {                                      
                    my_arr.push($(this).children().val());
                }               
            }else{           
                my_arr.push($(this).children().val());
            }
        })
        console.log(my_arr);
    })


})

本文标签: htmlJavaScript reading data into an array from a dynamic table of textfieldsStack Overflow