How to add an option like items per page with limit(dropdown with options 10,25,50) in the listing page.
It should be like show entries option in bootstrap datatables. I am using twbspagination.js for pagination. This is the sample link js-tutorials and given below is the source code.
<body>
<div class="container" style="padding:10px 20px;">
<h2>Pagination Example Using jQuery</h2>
<table id="employee" class="table table-bordered table table-hover" cellspacing="0" width="100%">
<colgroup><col width="20%"><col width="35%"><col width="40%"></colgroup>
<thead>
<tr>
<th>Name</th>
<th >Salary</th>
<th>Age</th>
</tr>
</thead>
<tbody id="emp_body">
</tbody>
</table>
<div id="pager">
<ul id="pagination" class="pagination-sm"></ul>
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
var $pagination = $('#pagination'),
totalRecords = 0,
records = [],
displayRecords = [],
recPerPage = 10,
page = 1,
totalPages = 0;
$.ajax({
url: "https://www.js-tutorials.com/source_code/api_data/employee_all.php",
async: true,
dataType: 'json',
success: function (data) {
records = data;
console.log(records);
totalRecords = records.length;
totalPages = Math.ceil(totalRecords / recPerPage);
apply_pagination();
}
});
function generate_table() {
var tr;
$('#emp_body').html('');
for (var i = 0; i < displayRecords.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + displayRecords[i].employee_name + "</td>");
tr.append("<td>" + displayRecords[i].employee_salary + "</td>");
tr.append("<td>" + displayRecords[i].employee_age + "</td>");
$('#emp_body').append(tr);
}
}
function apply_pagination() {
$pagination.twbsPagination({
totalPages: totalPages,
visiblePages: 6,
onPageClick: function (event, page) {
displayRecordsIndex = Math.max(page - 1, 0) * recPerPage;
endRec = (displayRecordsIndex) + recPerPage;
console.log(displayRecordsIndex + 'ssssssssss'+ endRec);
displayRecords = records.slice(displayRecordsIndex, endRec);
generate_table();
}
});
}
});
</script>
You can do this with below steps:
1) Add a drop down in your ui which show records per page, something like this:
<select id="recPerPage" onchange="apply_pagination();">
<option value="5">5</option>
<option value="10" selected='selected'>10</option>
<option value="20">20</option>
</select>
You can add this above or below the table as per your ui preferences.
Please note the dropdown should trigger the function apply_pagination onchange. I have added event handling inline just for reference. You should do it via addEventListner
2) In your code function apply_pagination() should get the current value of the recPerPage dropdown at the begining like this:
`recPerPage = $('#recPerPage').val();`
That should do the do the trick for you.
Your can also set the default value for recPerPage by replacing this:
recPerPage = 10,
with this:
recPerPage = $('#recPerPage').val(),
Update:
The pagination plugin you are using has a correct/updated version linked here
and
It has the dynamic total pages issue documented here , look for the heading "Dynamic Total number of pages"
Above should help you, I think.
Related
I have the following case that I am having a hard time solving.
In the image what I try to do is look for the documents of the selected process and that they are displayed in the table.
This is done with ajax, jsp and servlet.
For the select dropdown, this is the code where I list the processes through java and jsp classes.
<select class="form-control js-example-basic-single" name="sucursal">
<%
MantenedorProcesosLMD md = new MantenedorProcesosLMD();
List<procesoslmd> ld = md.listar_proc_lista(con);
for (procesoslmd p : ld) {
%>
<option value="<%=p.getLDM_ID()%>">
<%=p.getLDM_NOMBPROCESOS()%>
</option>
<%
}
%>
</select>
This is my code in sql where by means of the IDPROCESOS parameter I look for the documents.
SELECT
D.IDLDMDOCUMENTOS,
LT.NOMBRETIPO,RTRIM(D.LDM_NOMENCLATURA) AS NOMENCLATURA,
RTRIM(D.LDM_NOMBRE_DOCUMENTO) AS TITULO,
D.LDM_FECHA_SUBIDA,D.LMD_RUTA_DOCUMENTO
FROM LDM_DOCUMENTOS_ D
LEFT JOIN LDM_PROCESOS_ LP ON LP.IDLDMPROCESOS = D.IDLDMPROCESOS
LEFT JOIN LDM_TIPO_DOCUMENTO_ LT ON LT.IDTIPODOC = D.IDTIPODOC
WHERE LP.IDLDMPROCESOS = #IDLDMPROCESOS
But so far I can't get to the code to find the documents by clicking the search button, I'm trying to do it with ajax I'm still collecting information.
implement this ajax code where I get the value of my select dropdown the IDPROCESOS and if it brings me the documents so far I can show it in the console, but I want to add it to the table but when I click on the search button
$(document).ready(function () {
$('select[name=procesoldm]').on('change', function () {
$.ajax({
type: 'GET',
url: '../sv_proxdocumento',
data: 'codigoproceso='+$('select[name=procesoldm]').val(),
statusCode: {
404: function () {
alert('PAGINA NO ENCONTRADA');
},
500: function () {
alert('ERROR EN EL SERVIDOR');
}
},
success: function (dados) {
var pegadatos = dados.split(":");
console.log(pegadatos);
for (var i = 0; i < pegadatos.length -1; i++){
var codigodocumento = pegadatos[i].split("-")[0];
var nombretipo = pegadatos[i].split("-")[1];
console.log(nombretipo);
}
}
});
})
});
How do I pass that found data to a table with ajax, thanks for your time.
how it should look in the table when clicking the search button
You can use another for-loop after spliting your values and then on each iteration append td inside some variable using += and then add this generated html inside your table.
Demo Code :
$(document).ready(function() {
/*$('select[name=procesoldm]').on('change', function() {
$.ajax({
//other codes..
success: function(dados) {*/
//var pegadatos = dados.split(":");
//just for demo
var pegadatos = ["1-abc-abd-abdd-2/1/12", "2-abc2-abd2-abdd2-2/22/12", ""]
var html = ""; //declare this
//loop through main array
for (var i = 0; i < pegadatos.length - 1; i++) {
var values = pegadatos[i].split("-") //split values
html += `<tr>`
for (var j = 0; j < values.length; j++) {
html += `<td>${values[j]}</td>` //splited values..
}
html += `<td>--Visitor--</td>`
html += `</tr>`
}
$("table tbody").html(html) //add result inside tbody
/* }
});
})*/
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th>No</th>
<th>DocumentType</th>
<th>DocumentNaming</th>
<th>title</th>
<th>date</th>
<th>visitor</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I want to filter out table before loading it to reduce it's size that it would load faster, when its loaded i would like to let user to filter it. I am using public CDN script for filter part, but it does not work on content which is injected to . It only works if whole table is loaded together with page.. what i'am doing wrong?
Jsfilter: <script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tablefilter/2.5.0/tablefilter.js"></script>
DetailedRport.html
//this function called on button click it gets user and date to resize data set
<script type="text/javascript">
function myFunction() {
var y = document.getElementById("month-input").value;
var z = document.getElementById("email2").value;
//here is called server side script
google.script.run.withSuccessHandler(onSuccess).functionToRunOnFormSubmit(y, z);
}
//Resized data set gets injected to tbody
function onSuccess(c){
var table=toHTMLTable(c);
document.getElementById('myOutput1').innerHTML = table;
}
//Array to HTML table
function toHTMLTable(a) {
var content = a.map(function(row, i) {
var rowHTML = row.map(function (col) {
return "<td>" + col + "</td>";
}).join("");
return "<tr>" + rowHTML + "</tr>";
}).join("");
return content;
}
</script>
//user selects criteria for data table
<b> Report for:</b>
<select value="" name="email2" id="email2" width="300" autofocus="autofocus" autocorrect="off" autocomplete="off">
<?!= myEmails(); ?>
</select>
<b>Pick Period :</b>
<select name="Student" id="month-input" autofocus="autofocus" autocorrect="off" autocomplete="off">
<?!= myDates(); ?>
</select>
//On click table is loaded based on selection
<input type="button" value="Load Data" class="loadbutton" onclick="myFunction();" >
<br><br>
//Js tablefilter which should work but does not if table is injected
<table id="table1"class="mytable TF" cellspacing="0" cellpadding="0">
<thead>
<tr class="header">
<th style="width:5%;">TASK</th>
<th style="width:20%;">PROJECT</th>
<th style="width:30%;">DATE</th>
<th style="width:10%;">TIME SPENT</th>
<th style="width:10%;">WORDCOUNT</th>
<th style="width:10%;">SPEED</th>
</tr>
</thead>
//Where data table is injected
<tbody id="myOutput1">
</tbody>
</table>
//Setting Js tablefilter source http://tablefilter.free.fr/
<script language="javascript" type="text/javascript">
var tf = setFilterGrid("table1");
</script>
server.gs
// here data set gets filtered based on users selection and is sent back
// Using ArrayLib library
function functionToRunOnFormSubmit(y,z) {
var ss = SpreadsheetApp.openById(id);
var ActiveSheet = ss.getSheetByName("TogglMap");
var StartRow = 2;
var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
var EMWholeRange = ActiveSheet.getRange(StartRow,2,RowRange,13);
var AllValues = EMWholeRange.getDisplayValues();
var dat = y +'-01'
var removeCol = function(arr, colIndex, colIndex2) {
for (var i = 0; i < arr.length; i++) {
var row = arr[i];
row.splice(colIndex, colIndex2);
}
}
removeCol(AllValues, 5 , 6);
var filteredArr1 = ArrayLib.filterByText(AllValues, 1, z)
var filteredArr2 = ArrayLib.filterByText(filteredArr1, 3, dat)
removeCol(filteredArr2, 1 ,1);
Logger.log(AllValues)
return filteredArr2
};
My goal is working JS filter
I am trying to use the esimakin jQuery Pagination plugin to break my table up into multiple pages because it is getting its data from an ever growing database. However my pagination bar does not:
Split table into pages
Change pages when I click next or previous.
Any advice would be much appreciated.
HTML:
<div class="table-responsive">
<div class="form-group pull-right">
<input type="text" id="myInput" onkeyup="filterTable()" class="search form-control" placeholder="Filter Table">
</div>
<div class="form-group pull-left">
Load Selected
</div>
<table id="draftTable" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th data-field="radio"></th>
<th data-field="bulletin_id">Bulletin ID</th>
<th data-field="event">Event</th>
<th data-field="badge_num">Badge Number</th>
<th data-field="AYEAR">Year</th>
</tr>
<tbody>
</tbody>
</thead>
</table>
</div>
<ul id="pagination" class="pagination-sm pull-right"></ul>
</div>
</div>
JS:
<script>
$(document).ready(function(){
populateTables('S');
});
function populateTables(res){
console.log(res)
$.getJSON("bulletinListJSON.asp", {res:res}, function(data){
}).done(function( data ) {
for (var i=0;i<=data.length;i++){
var draftData = "<tr><td><input type=radio value="+ i + " name=load id=load /></td><td>" + data[i].BULLETIN_ID + "</td><td>" + decodeURIComponent(data[i].EVENT) + "</td><td>" + data[i].BADGE_NUM + "</td><td>" + data[i].AYEAR + "</td></tr>";
$('#draftTable').find('tbody').append(draftData);
}
});
}
function filterTable(event) {
var filter = event.target.value.toUpperCase();
var rows = document.querySelector("#draftTable tbody").rows;
for (var i = 0; i < rows.length; i++) {
var firstCol = rows[i].cells[1].textContent.toUpperCase();
var secondCol = rows[i].cells[2].textContent.toUpperCase();
var thirdCol = rows[i].cells[3].textContent.toUpperCase();
var fourthCol = rows[i].cells[4].textContent.toUpperCase();
if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1 || thirdCol.indexOf(filter) > -1 || fourthCol.indexOf(filter) > -1) {
rows[i].style.display = "";
} else {
rows[i].style.display = "none";
}
}
}
document.querySelector('#myInput').addEventListener('keyup', filterTable, false);
$("#draftTable tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:second').html();
alert(value);
});
$('.ok').on('click', function(e){
alert($("#table tr.selected td:first").html());
});
//Pagination
$('#pagination').twbsPagination({
totalPages: 35,
visiblePages: 7,
items: 20,
itemOnPage: 8,
});
</script>
search in google:
jq dataTables
Wery nice table.
Search, Download (Excel, word, pdf), order column, server side or cliend side run, more more....
İm use this. 15 million rows.
The twbs-pagination plugin provides an onPageClick callback option; you'll need to implement that.
You could also dynamically set the total number of page based on the length of the response data.
A snippet from a simple gist based on your situation.
function setContent( page ) {
// generate markup to display
$('#page-content').html(data[page]);
}
$('#pagination').twbsPagination({
totalPages: data.length, // from $.ajax response
visiblePages: 7,
onPageClick: function (event, page) {
setContent(page);
}
});
I have a jsp with a bootstrap wizard, like this:
http://s3.amazonaws.com/creativetim_bucket/products/22/original/wizard_template.png?1407329794
With this wizard, I can add the employees element collected in Javascript array (I also use AngularJS).
After that, in the last step of wizard there is the summary of the employees shown in a table.
For each row of the table, I have been added an href link to delete the current employee element. This href link calls a function managed by AngularJS.
Ok, it work. But, after the deletion, the table is not refresh. And the deleted element is present in table yet, but not in array.
So, how can I refresh the table?
Here's the code of the table:
<table class="table table-bordered table-hover table-condensed">
<thead>
<tr>
<td>#</td>
<td>Nome</td>
<td>Cognome</td>
<td>Matricola</td>
</tr>
</thead>
<tr ng-repeat="employee in listaDipendenti track by $index">
<td>{{$index + 1}}</td>
<td>{{employee.nome}}</td>
<td>{{employee.cognome}}</td>
<td>{{employee.matricola}}</td>
<td><a ng-click="DeleteEmployees($index)" href="#" class="btn btn-simple btn-xs" role="button" style="color: green">Delete</a></td>
</tr>
</table>
Here's the code in JS:
//Classe di tipo Employee
function Employee(nome, cognome, matricola) {
this.nome = nome;
this.cognome = cognome;
this.matricola = matricola;
}
var listEmployees = [];
var nDip = 0;
function Controller($scope) {
$scope.DeleteEmployees = function (n) {
if (n > -1) {
listEmployees.splice(n, 1);
}
};
}
for #charlietfl
It's not right, look the function used to add an employee in JS array.
$scope.AddInList = function () {
var nome = $("#nome").val();
var cognome = $("#cognome").val();
var matricola = $("#matricola").val();
$("#nome").val("");
$("#cognome").val("");
$("#matricola").val("");
nDip = nDip + 1;
listEmployees.push(new Employee(nome, cognome, matricola));
$("#cont").text(nDip);
$scope.listaDipendenti = JSON.parse(JSON.stringify(listEmployees));
};
Please can someone tell me why the first row gets and index value of 1 but every other new row also get 1 instead of 2,3,4 and so on.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
</head>
<body>
<form>
<table>
<thead>
<tr>
<th scope="col">Track</th>
<th scope="col">Album</th>
<th scope="col">Artist</th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="track[0]" id="track"></td>
<td><input name="album[0]" id="album"></td>
<td>
<select name="artist[0]" id="artist">
<option value="">Please select</option>
<option value="1">Joe Bloggs</option>
<option value="2">Jack Bloggs</option>
<option value="3">Tina Bloggs</option>
</select>
</td>
</tr>
</tbody>
</table>
</form>
<button>Add Row</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function($)
{
// trigger event when button is clicked
$("button").click(function()
{
// add new row to table using addTableRow function
addTableRow($("table"));
// prevent button redirecting to new page
return false;
});
function addTableRow(table)
{
var $tr = $(table).find("tr:last").clone();
alert($tr);
var fname = $("#track").attr("name");
var nid = fname.match(/\[(.*?)\]/g);
var idx = nid[0];
idx = idx.replace(/[[\]]/g,'')
var n = fname.split("[");
idx = parseInt(idx) + 1;
$tr.find("input,select").attr("name", n[0] + "[" + idx + "]");
$(table).find("tbody tr:last").after($tr);
};
});
</script>
</body>
I cant seem to work out how to add a new row every time increasing the "name" of each table element by 1 every time ready to use an AJAX post.
The new rows are being created wrong. Artist and Album elements name are always track[0]
Wouldn't be easier to do something like this?
function addTableRow(table) {
var index = $(table).find("tbody tr").length;
var $tr = $(table).find("tr:last").clone();
$tr.find("input,select").each(function (i, k) {
var old_name = $(k).attr("name");
var new_name = old_name.replace(index-1, index);
$(k).attr("name", new_name);
});
$(table).find("tbody tr:last").after($tr);
};
DEMO
Also, consider to give a class instead of a id in every input/select and give a id to the row. It would be easier to work with. as #HMR said when cloning the tr the inputs and select id's are cloned as well, adding the row then causes multiple elements with the same id's. This is not good, make sure each element as a unique ID
How about just counting tr in the tbody instead:
function addTableRow(table)
{
var $tr = table.find("tbody").find("tr").last().clone();
var fname = $("#track").attr("name");
var nid = fname.match(/\[(.*?)\]/g);
var new_idx = table.find('tbody').find('tr').length;
var n = fname.split("[");
idx = parseInt(idx) + 1;
$tr.find("input,select").attr("name", n[0] + "[" + new_idx + "]");
$(table).find("tbody tr:last").after($tr);
};