Overview
Application Scenario
You can sort the table data when filling in a form, but if Sort After Expansion is used, each time you click the table header to sort, the page is refreshed, causing the data just filled in to be lost.
To solve this problem, you can use JavaScript to sort data without refreshing the page, as shown in the following figure.
Implementation Method
Use JavaScript to sort the data on the page.
Example
Template Preparation
Create a template. Create a dataset using the SQL statement SELECT * FROM SProduct WHERE ProductID < 20.
Drag fields from the dataset into cells, add text widgets, and set the style, as shown in the following figure.
Event Adding
Choose Template> Web Attribute> Data Entry Setting, select Set for This Template Separately, and add a loading end event.
JavaScript codes are as follows:
//Sorting method. The parameters are the table ID and the table column.
function sortTable(table, idx) {
var otable = document.getElementById(table),
otody = otable.tBodies[0],
otr = otody.rows,
tarr = [];
for (var i = 1; i < otr.length; i++) {
tarr[i - 1] = otr[i];
};
if (otody.sortCol == idx) {
tarr.reverse();
} else {
tarr.sort(function (tr1, tr2) {
var value1 = tr1.cells[idx].innerHTML;
var value2 = tr2.cells[idx].innerHTML;
if (!isNaN(value1) && !isNaN(value2)) {
return value1 - value2;
} else {
return value1.localeCompare(value2);
}
})
}
var fragment = document.createDocumentFragment();
for (var i = 0; i < tarr.length; i++) {
fragment.appendChild(tarr[i]);
};
otody.appendChild(fragment);
otody.sortCol = idx;
}
//Get the table header on the page and set the click event.
$("#r-0-0 td").bind("click",function(){
//Get the clicked column.
var a=$(this).attr("col");
//Call the sorting method and pass the value.
//0 is the table ID, which can be obtained by using F12.
sortTable('0',a);
});
Effect Display
On PC
Save the template and click Data Entry Preview. Then the preview effect is shown in the following figure.
On Mobile Terminals
It is not supported on mobile terminals.
Template Download
You can download the example template. Sorting data without refreshing the page.cpt
Notes
The above solution is not highly compatible as some columns do not have the col attribute, and the report ID may not be 0. Here a more compatible solution is provided as follows:
1. Remain the code for sorting in the upper part unchanged.
2. Replace the lower part of the code with the following codes.
//Get the table header on the page and set a click event.
$("#r-0-0 td").bind("click", function() {
//Get the index of the clicked column.
var index = $(this).parents("tr").find("td").index($(this));
//Get the ID of tables in the div element in class=page-block.
var tableID = $("div.page-block table").attr("id");
//Call the sorting method and pass the value.
//0 is the ID of the table, which can be obtained by using F12.
sortTable(tableID, index);
});