jQueryMobile: refresh after dynamically adding rows to a table with column toggle

Dominik picture Dominik · Jun 4, 2013 · Viewed 14.3k times · Source

I have a problem regarding the jQueryMobile "column toggle table mode".

After adding rows dynamically via Javascript, the toggling gets wrong. Not that it doesn't work at all, but it somehow gets confused, swaps columns or similar strange behaviour.

I am fully aware that there is a "refresh"-method exactly for this scenario, but it doesn't work in my example. I also looked at How to refresh JQuery mobile table after a row is added dynamically, but it doesn't really apply to my problem. The only other similar question I found was old and related to version <=1.3.0 of JQM, when no refresh-method existed.

I have this table

<table data-role="table" id="table" data-mode="columntoggle" class="ui-body-d ui-shadow table-stripe ui-responsive" data-column-btn-theme="b" data-column-btn-text="Columns to display..." data-column-popup-theme="a">
            <thead>
                <tr class="ui-bar-d">
                    <th data-priority="1">#</th>
                    <th data-priority="1">Data Code</th>
                    <th>Data Name</th>
                    <th>Value</th>
                    <th data-priority="1">Minimum</th>
                    <th data-priority="1">Maximum</th>
                </tr>
            </thead>
            <tbody>
            ...
            </tbody>
</table>

And this Javascript code that updates it:

for (var i = 0; i < rows.length; i++) {
    html = html + "<tr>\n";
    for (var j = 0; j < rows[i].length; j++) {
        html = html + "<td>" + rows[i][j] + "</td>\n";
    }
    html = html + "</tr>\n\n";
}

$("#table > tbody").append(html);
$("#table").table("refresh");

.


Please see this JSFiddle for a minimized -but working- demo of my problem: http://jsfiddle.net/kkppd/


If you try the JSFiddle, please compare it to my findings:

  1. "Run" the code. The webpage should show up with some sample data which is hardcoded in the HTML. The columns are toggling correctly.
  2. Click the button that triggers an update similar to the way it would be updated automatically in my original application. This empties the table and re-adds the same content. Afterwards I call the refresh-method of JQM.
  3. The table seems as it was before - but have a try on the "toggle columns" button: "Maximum" toggles "Minimum", "Minimum" toggles "#", "#" toggles "Data Code", etc.

What did I do wrong?

Answer

Blue picture Blue · Jul 18, 2013

I had the same problem. After a bit of hacking through the JQueryMobile code, I've came with this workaround:

$("#table > tbody").append(html);
$("#table").table("refresh");

// Code to add
var columnIndex = 0;
$("#table-popup fieldset").find("input").each(function(){
     var sel = ":nth-child(" + (columnIndex + 1) + ")";
     $(this).jqmData("cells", $("#table").find("tr").children(sel));
     columnIndex++;
});