Tablesorter bug with pagination and AJAX - javascript

I'm using JS tablesorter in my table, who is populate with AJAX using the append method;
So, when I'm in the page 1, the tablesorter works great. But when I'm in the page 2 or +, a bug appears cause its is sorting the rows of every page before that I'm in.
this is my AJAX who populate the table:
function getData(page){
totalclientes =0;
totalclientes = 0;
var url = "../getters/getAtivosPainel.php?Lojas&offset="+page;
var data = "";
$.get(url, function(response){
serverResponse = response;
console.log(response);
for(i in response.content){
data +='\
<tr>\
<td>'+response.content[i].LojaNome+'</td>\
<td>'+response.content[i].LojaBairro+'</td>\
<td>'+response.content[i].LojaTelefone1+'</td>\
<td>'+LojaStatus+'</td>\
<td>'+response.content[i].PlanoNome+'</td>\
<td>'+response.content[i].Diferenca+'</td>\
</tr>';
}
$('#corpotabela').empty();
$('#corpotabela').append(data);
$('#qtd').empty();
$('#qtd').append(response.count);
$('table').tablesorter();
var width = new Array();
$(".table-body tr:eq(0)").find('td').each(function (position){
width[position] = $(this).outerWidth();
});
$(".table-header tr").find('th').each(function (position){
$(this).css("width", width[position]+2);
});
});
}
And this one is my table
<table class="table table-bordered table-hover" id="table">
<thead style="border: 1px solid #ddd;" >
<tr style="cursor: pointer;">
<th>Nome</th>
<th>Bairro</th>
<th>Telefone</th>
<th>Status</th>
<th>Plano</th>
<th>Dias para fim do plano</th>
<th>Ações</th>
</tr>
</thead>
<tbody id="corpotabela">
</tbody>
</table>
</div>
<div style="text-align:left; margin-top: -25px;">
<nav id="navi">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<?php
$j = 0;
$k=1;
for($i =$cnt; $i > 0; $i--) {
echo '<li><a id="datas" href="javascript:getData('.$j.')">'.$k.'</a></li>';
$j = $j+30;
$k++;
}
?>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
Can you give me a help?

You should only initialize tablesorter once.
$(function(){
$('table').tablesorter();
var getData = {
// add rows here
$('table').trigger('update');
};
});
When new data is added, use $('table').trigger('update'); to signal tablesorter that the content has been changed.

Related

thymeleaf Springboot Page not refresh When I click next (preview) button in fragment

I’m use my fragment to refresh data in table when I enter page and input filter keyword.
If I’m not add the js to build the enter next page, it is work correct in enter page show list.
(I have certify my controller and service is okey)
But when I add the ajax to fetch(post) data and refresh data in table, the next page number still not auto refresh.(/[[${response.number}]]/ not refresh, still 1)
is adding something after ajax code in fragment or js?
where are the mistake ? thank you.
.....
.....
<div class="col-sm-3 my-1">
<label class="sr-only" for="inlineFormInputName">Name</label> <input
type="text" class="form-control" id="inlineFormInputName"
placeholder=“u”serName>
</div>
......
......
<div class="row mt-5">
<div class="col">
<div th:fragment="filteredList" id="filteredList">
<table class="table table-responsive table-hover"
id="devicesTable">
<tbody>
<tr th:each="users,iter : ${response.content}">
<td class="text-info text-center"
th:text=“${users.name}"></td>
<td class="text-left" th:text="${users.department}"></td>
<td class="text-center"
th:text="${#dates.format(users.updateTime, 'yyyy-MM-dd hh:mm:ss')}"></td>
</tr>
</tbody>
</table>
<nav aria-label="Page navigation" class="mt-4">
<ul class="pagination justify-content-center">
<li class="page-item"
th:classappend="${response.isFirst()} ? disabled: '' "><a
id="firstPageBtn" class="page-link" href="javascript:void(0);">firstPage</a>
</li>
<li class="page-item"
th:classappend="${response.isFirst()} ? disabled: '' "><a
id="prePageBtn" class="page-link" href="javascript:void(0);">Pre Page</a>
</li>
<li class="page-item"
th:classappend="${response.isLast()} ? disabled: '' "><a
id="nextPageBtn" class="page-link" href="javascript:void(0);">Next Page</a>
</li>
<li class="page-item"
th:classappend="${response.isLast()} ? disabled: '' "><a
id="lastPageBtn" class="page-link" href="javascript:void(0);">Last Page</a>
</ul>
</nav>
.....
.....
<script th:inline="javascript">
$('#inlineFormInputName').on('keyup', function() {
var myvalue = $(this).val();
fetchListData(myvalue, 0);
});
$(document).on('click','#firstPageBtn',function(){
var inputKeyword = $('#inlineFormInputName').val()
var currentPageNumber = 0;
fetchListData(inputKeyword, currentPageNumber)
});
$(document).on('click','#prePageBtn',function(){
var inputKeyword = $('#inlineFormInputName').val()
var currentPageNumber = /*[[${response.number-1}]]*/0;
fetchListData(inputKeyword, currentPageNumber)
});
$(document).on('click','#nextPageBtn',function(){
var inputKeyword = $('#inlineFormInputName').val()
var currentPageNumber = /*[[${response.number}]]*/0;
currentPageNumber = currentPageNumber +1;
fetchListData(inputKeyword, currentPageNumber)
});
$('#lastPageBtn').click(function(e) {
var currentPageNumber = /*[[${response.totalPages-1}]]*/0;
fetchListData(inputKeyword, currentPageNumber)
});
function fetchListData(myvalue, page) {
/*<![CDATA[*/
var baseUrl = "/filterUsersListByKeyword";
var fullUrl = new URL(baseUrl, document.location);
fullUrl.searchParams.append("type", 1);
fullUrl.searchParams.append("name", encodeURI(myvalue));
fullUrl.searchParams.append("userId", "id0001"); //fake data
fullUrl.searchParams.append("page", page);
fullUrl.searchParams.append("size", 6);
/*]]>*/
$.ajax({
url : fullUrl,
type : 'POST',
success : function(response) {
$('#filteredList').html(response);
}
})
}
</script>

jQuery : Trigger event on dynamic content

i am trying to use the dynamic table at
https://codepen.io/ashblue/pen/mCtuA
I want to have a button that deletes all rows from the table. SO basically, fire the click function on all instances of the class .table-remove
i tried to do the following
function deleteAll() {
jQuery('.table-remove').each(function() {
var currentElement = $(this);
console.log(currentElement);
currentElement.trigger('click');
});
}
where the click is defined as
$('.table-remove').click(function() {
console.log("triggered");
$(this).parents('tr').detach();
});
but nothing happens when i call the deleteAll function. i dont even se anything on the console
am i doing this right?
I want to have a button that deletes all rows from the table. So basically, fire the click function on all instances of the class .table-remove.
You could do it that way but it's far simpler to organise your table into :
a <thead> containing the header row
a <tbody> containing the visible row(s)
a <tbody> containing the row template
Thus, the code behind the "Delete All" button can very simply select all rows in the first <tbody> and .remove() them.
HTML
<div class="container">
<h1>HTML5 Editable Table</h1>
<p>Through the powers of <strong>contenteditable</strong> and some simple jQuery you can easily create a custom editable table. No need for a robust JavaScript library anymore these days.</p>
<ul>
<li>An editable table that exports a hash array. Dynamically compiles rows from headers</li>
<li>Simple / powerful features such as add row, remove row, move row up/down.</li>
</ul>
<div id="table" class="table-editable">
<span class="table-add glyphicon glyphicon-plus"></span>
<table class="table">
<thead> <!-- <<<< wrap the header row in <thead>...</thead> -->
<tr>
<th>Name</th>
<th>Value</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody class="main"> <!-- <<<< wrap the visible row(s) in <tbody>...</tbody> -->
<tr>
<td contenteditable="true">Stir Fry</td>
<td contenteditable="true">stir-fry</td>
<td>
<span class="table-remove glyphicon glyphicon-remove"></span>
</td>
<td>
<span class="table-up glyphicon glyphicon-arrow-up"></span>
<span class="table-down glyphicon glyphicon-arrow-down"></span>
</td>
</tr>
</tbody>
<tbody class="hide"> <!-- <<<< wrap the template row in its own hidden <tbody>...</tbody> -->
<tr>
<td contenteditable="true">Untitled</td>
<td contenteditable="true">undefined</td>
<td>
<span class="table-remove glyphicon glyphicon-remove"></span>
</td>
<td>
<span class="table-up glyphicon glyphicon-arrow-up"></span>
<span class="table-down glyphicon glyphicon-arrow-down"></span>
</td>
</tr>
</tbody>
</table>
</div>
<button id="export-btn" class="btn btn-primary">Export Data</button>
<button id="deleteAll-btn" class="btn btn-primary">Delete All</button>
<p id="export"></p>
</div>
Another aspect is how best to attach click handlers to the three row actions - delete, move-up and move-down.
As the rows are created/appended dynamically, the way to go is to delegate click handling to a container (eg the table) using jQuery's $(static-container).on(event, descendent-selector, handler). This will attach the desired actions to all current rows, and future rows just by appending them.
Javascript
jQuery(function($) {
var $TABLE = $('#table table');
var $BTN = $('#export-btn');
var $BTN2 = $('#deleteAll-btn');
var $EXPORT = $('#export');
$('.table-add').on('click', function() {
$('tbody.hide tr', $TABLE).clone(true).appendTo($('tbody.main', $TABLE));
});
$TABLE.on('click', '.table-remove', function() { // delegate row removal to the table
$(this).closest('tr').remove();
});
$TABLE.on('click', '.table-up', function() { // delegate row-up movement to the table
var $row = $(this).closest('tr');
$row.insertBefore($row.prev());
});
$TABLE.on('click', '.table-down', function() { // delegate row-down movement to the table
var $row = $(this).closest('tr');
$row.insertAfter($row.next());
});
$BTN.on('click', function() {
var $headers = $('thead th', $TABLE).not(':empty').map(function() {
return $(this).text().toLowerCase();
});
var $data = $('tbody.main tr', $TABLE).map(function() {
var $td = $(this).find('td'),
h = {};
$headers.each(function(i, header) {
h[header] = $td.eq(i).text();
});
return h;
});
$EXPORT.text(JSON.stringify($headers.get().concat($data.get())));
});
$BTN2.on('click', function deleteAll() {
$("tbody.main tr", $TABLE).remove();
});
});
DEMO.
If the goal is just to remove the rows, you can do that directly without triggering each individual click event:
function deleteAll() {
$('.table-remove').closest('tr').remove()
}
If you really need to trigger the click event on each '.table-remove' element, you would do that like so:
function deleteAll() {
$('.table-remove').each(function() {
$(this).trigger('click')
});
}
(...which is roughly equivalent to your existing code. I'm not sure why your existing code isn't working for you; perhaps it's down to your use of jQuery() instead of the $() alias, or you're just not calling the deleteAll() function successfully?)

customize the code for tab view with using href

Actual html file
It is coded for table but i need it for anchor
<table>
<tr>
<td>click me</td>
</tr>
<tr>
<td>click me</td>
</tr>
<tr>
<td>click me</td>
</tr>
<tr>
<td>click me</td>
</tr>
<tr>
<td>click me</td>
</tr>
</table>
script.JS
var rows = document.getElementsByTagName('tr');
function rowHighlight() {
var selectedRows = document.getElementsByClassName('selected');
for (var n = 0; n < selectedRows.length; n++) {
selectedRows[n].className = '';
}
this.className = 'selected'
}
for (var i = 0; i < rows.length; i++) {
rows[i].addEventListener('click', rowHighlight);
}
css file
.selected {
background-color:red;
}
table:hover {
cursor:pointer;
}
The above code are the actual code but i want to customize it for my below code
html file
it is my code for tab view in ionic
<div class="tabs">
<a ng-class="tab-item" ng-click="a('top')">
Top News
</a>
<a ng-class="tab-item" ng-click="a('latest')">
Latest News
</a>
<a ng-class="tab-item" ng-click="a('popular')">
Popular News
</a>
</div>
<div>
Here is the fiddle!
.red
{
background-color:red;
}
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js'></script>
<div class="tabs" ng-app>
<a ng-class='{"red":tog==1}' ng-click='tog=1'>
Top News
</a><br/>
<a ng-class='{"red":tog==2}' ng-click='tog=2'>
Latest News
</a><br/>
<a ng-class='{"red":tog==3}' ng-click='tog=3'>
Popular News
</a>
</div>
Hope it helps!

JavaScript for each record in my view

I have a VIEW where I display a table with 15 records (15 rows) and 5 columns, but the very thing that matters is a column, "Actions". In it I have 1 button, "Preview", that when clicking, I want to open a window with a message, for tests.
However, only the first record, when clicking the "View" button, displays the message window, the other 14 records do not.
How do I make all records / lines display the message?
Follow the code below:
<table class="table table-bordered table-hover tablesorter">
<thead>
<tr>
<th class="header text-center" style="width: 100px;"> Ações </th>
</tr>
</thead>
<tbody id="tabela">
#foreach (var item in Model)
{
<tr>
<td>
#this.Hidden("IdClient").Value(item.Id)
<a id="visualizarCliente" class="btn btn-primary btn-xs btn-visualizar" data-toggle="tooltip" title="Visualizar" target="_blank"
href="#Url.Action(MVC.Painel.Clientes.Visualizar(item.Id))">
<i class="fa fa-eye"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
$(function () {
$("#visualizarCliente").click(function () {
var idCliente = $("#IdClient").val();
window.alert("Teste");
})
});
</script>
The problem is that you are using the id selector and it can not be repeated. Switch to any other selector, such as data-toggle = "tooltip" for example.
<script type="text/javascript">
$(function () {
$("a[data-toggle='tooltip']").click(function () {
window.alert("Teste");
})
});
</script>
The problem is ID which always be used for something UNIQUE. Try to use CLASS instead. Your function should goes something like this one example:
$(function () {
$(".btn-visualizar").click(function () {
var idCliente = $(this).parent().find("#IdClient").val();
window.alert("Teste");
})
});
In the given example the line $(this).parent().find("#IdClient").val(); specifies that this would be it's nearest element value as it should be.

how to push table selections to array: jquery

Summary: I have a html page which consists of two add buttons and two tables. When add button is clicked, rows are appended to respective table. In the back end i want to collect all the row elements when "button" is clicked and POST to other page.
<div class="report">
<div class="panel">
<div>
<button type="button" class="add btn btn-primary" data-toggle="tooltip" title="Add to configuration list.">
<i class="fa fa-plus"></i>
Add
</button>
</div>
<div class ="configuration-table panel-body">
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>Remove</th>
<th>Layer</th>
<th>Display</th>
<th>Unit</th>
<th>Dataset</th>
<th>Ordering</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div class = "done">
<input class="btn btn-success" formaction="{% url 'something' %}" formmethod="post" type="submit" value="Done"></input>
</div>
</div>
and here is reports.js
var arr = [];
$('.report')
.on('click','.add', function(){
$(this)
.parents('.report')
.find('.configuration-table tbody')
.append(
'<tr>'+
'<td class="remove-row" role="button" aria-label="Remove Region"><i class="fa fa-times" title="Remove this row." data-toggle="tooltip" data-placement="right" aria-hidden="true"></i></td>'+
'<td>'+layer_text+'</td>'+
map_elements+
'<td>'+unit_text+'</td>'+
'<td>'+dataset_text+'</td>'+
'<td class="ordering" aria-label="Re-order"><i class="fa fa-arrows" title="Re-arrange row order." data-toggle="tooltip" data-placement="right"></i></td>'+
'</tr>'
)
.on('click','.remove-row',function() {
$(this).parents('tr').remove();
})
.sortable({
helper: script
})
.disableSelection();
.on('submit','.done form',function(){
//do domething to collect columns
$('.configuration-table tbody').each(function(){
arr.push({
column.name: column.value
});
});
})
Here as you can see that table rows can be removed/sortable. Dont worry about POST method now. I just need the logic to collect columns from the table after done button is clicked.
Assume script is correct in terms of class names and traversal-filters. I just need the logic to collect column elements and push to "arr".
Thanks in advance
Firstly, you need to loop over the th elements within the thead to get the column names, then the tr in the tbody to get the values. You can get the text() properties from each respective td to fill object. Try this:
.on('submit','.done form',function() {
var arr = [];
var $table = $('.configuration-table');
var columnNames = $table.find('thead th').map(function() {
return $(this).text();
});
$table.find('tbody tr').each(function(){
var rowValues = {};
$(this).find('td').each(function(i) {
rowValues[columnNames[i]] = $(this).text();
});
arr.push(rowValues);
});
});
Example fiddle

Categories

Resources