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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22447506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:10:55  来源:igfitidea点击:

JavaScript reading data into an array from a dynamic table of textfields

javascripthtmlarraysdynamichtml-table

提问by user2461876

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.

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

Here is my current HTML code.

这是我当前的 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>

Here is my JavaScript file:

这是我的 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); 
}

采纳答案by TameBadger

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

我尽量保持简单,也可以说是 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);

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 recommend continuing that, if you want to peak into a bigger codebase I would recommend 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.

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

回答by Justin Domnitz

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.

我重新设计了 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);

回答by user385729

Is this what you are looking for?

这是你想要的?

JSFIDDLE

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


})