JavaScript从动态文本字段表中将数据读入数组

时间:2014-03-17 05:23:05

标签: javascript html arrays dynamic html-table

我使用HTML表格动态创建表格,并使用JavaScript函数附加到按钮点击。我现在想要使用名为finished的另一个按钮获取数据并将其存储到多维数组中(如果可能)。我甚至无法开始使用最后一种方法将其保存到数组中。我无法弄清楚如何检索文本数据。

这是我目前的HTML代码。

<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>

这是我的JavaScript文件:

 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); 
}

3 个答案:

答案 0 :(得分:2)

我重新设计了TameBadger的答案,即按行而不是按列构建数组。我还添加了一个检查,以查看给定单元格在引用之前是否具有值。就我而言,并非所有细胞都有值。

 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);

答案 1 :(得分:1)

我试着保持简单,并且jQuery干净,可以这么说。

    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);

第二次修订

 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);

很高兴你自己开始做桌面操作,我建议你继续这样做,如果你想进入更大的代码库,我建议你查看jTable's。即使它是一个jQuery插件,你仍然可以通过查看代码结构来学习一些东西,以便根据数据集和添加记录等处理构建表的所有逻辑。

答案 2 :(得分:1)

这是你在找什么?

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);
    })


})
相关问题