js gets the value of the input in the Table form

1. js gets the value of the input in the Table table

  • There are a large number of example sentences on the Internet to obtain the input value in the Table table, but none of them meet the author's requirements, so Yu Liang wrote a general method for reference. Maybe you will use it, and I may use it again in future projects, so write the following content.
  • I have such a structure in my project. The child nodes of each cell in the Table table have an Input label, and the content of these labels can be modified at will. The number of cases is only two columns. As shown below

insert image description here

1. Obtain the value of the sub-label input in the Table table cell

The idea of ​​this example is to only get cells with values, and cells without values ​​will not be admitted.
Some are shown below js代码片.

/**
 * @function 获取Table单元格Input的值
 * @param {string} 参数 tableId 
 * @returns 返回数组
 * @desription 说明:参数为Table的id值
 */
function getTableValue(tableId) {
    
    
    var tableArr = [];
    var name;
    var val;
    var obj = document.getElementById(tableId);
    //循环Table行数  
    for (var i = 0; i < obj.rows.length; i++) {
    
    
        if (obj.rows[i].cells[0].childNodes[0].value) {
    
    
            name = obj.rows[i].cells[0].childNodes[0].value
        }
        if (obj.rows[i].cells[1].childNodes[0].value) {
    
    
            val = obj.rows[i].cells[1].childNodes[0].value;
        }
        if (name && val) {
    
    
            var cellVal = {
    
     "name": name, "val": val };
            tableArr.push(cellVal);
        }
    }
    //console.log('tableArr', tableArr);
    return tableArr;
}

The obtained result is shown in Figure 2:
insert image description here

2. Call method

Some are shown below js代码片.

var tableId = "tablePop";
var tableVal = getTableValue(tableId);

3. Description

The parameter in the calling method is the id of the table label. Because there are many tables in my project that need to be called multiple times, I wrote a general method
to show some below Html代码片.

<table class="table table-bordered border-primary mt-2 table-responsive" id="tablePop">
     <tr class="m-0 p-0">
        <td class="m-0 p-0"><input class="form-control m-0 p-0" type="text"  style="font-size: 12px;" value=""></td>
        <td class="m-0 p-0"><input class="form-control m-0 p-0" type="text"  style="font-size: 12px;" value=""></td>
     </tr>
 </table>

4. Postscript

It is even simpler to get all the cell contents, just add a column loop.

Guess you like

Origin blog.csdn.net/weixin_43727933/article/details/129000460