简体   繁体   中英

Getting data from html table with dynamic ip and filling the data in javascript object

I have a page that creates multiple tables dynamically 'all with static table class name', but each table does have a unique id name.

Users can edit each table and then save the changes on submit. What is required is that the data in the amended table will be selected and sent to the server. I implemented the code using a single table with the class name, which worked perfectly, below is the code:

    var rows = [].slice.call($('.TableStaticClassName')[0].rows);

    var keys = [].map.call(rows.shift().cells, function (e) {
        return e.textContent.replace(/\s/g, '');
    });

    var result = rows.map(function (row) {
        return [].reduce.call(row.cells, function (o, e, i) {
            o[keys[i]] = e.textContent;
            return o;
        }, {})
    });

The problem is when I tried to use this code when having multiple tables. What i have now looks like this for example:

<table class="TableStaticClassName" id="12345"></table>
<table class="TableStaticClassName" id="23456"></table>
<table class="TableStaticClassName" id="34567"></table>

When I have multiple tables I wont be able to use the table class name since it will select the data from all the tables. So when i try to select the data from a single table using the table id with code like the below

var x = document.getElementById("12345").rows[0].cells.length;

or even the example I use on single tables like

var rows = [].slice.call($('#12345')[0].rows);

I get an error 'TypeError: undefined is not an object' and I'm not able to read the row content of the changed table. I tried different solutions and implementations, but they all ended up giving me the same error.

Any help would be appreciated. Thank you in advance

I actually found a solution that worked, so I'm going to post it in case someone had the same problem in the future. The solution was to combine both the id along with the class name, below is the code snippet.

var rows = [].slice.call($('#'+dynamicGeneratedIdVariable+'.TableStaticClassName')[0].rows);

        var keys = [].map.call(rows.shift().cells, function (e) {
            return e.textContent.replace(/\s/g, '');
        });

        var result = rows.map(function (row) {
            return [].reduce.call(row.cells, function (o, e, i) {
                o[keys[i]] = e.textContent;
                return o;
            }, {})
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM