I need to perform a pagination where I need to display 5 rows every time. First 5 rows are displayed. On the second click, the next 5, the third rows no. 11-15, and so on. I need to display even if at least one row is there (after n clicks where totalRows mod 5 is less than 5). I do not get this.
function rightArrow()
{
pageCount = document.getElementById('pgCnt').value; //totalRows / 5
totCount = document.getElementById('totCnt').value; //totalRows
currPage = tempRows - pageCount + 2; //current set of rows
document.getElementById('tempPage').value = tempPage;
var m = totCount%5;
if(pageCount != tempRows)
m = 5;
else
{ m = (totCount % 5) - 1;
document.getElementById('rightArr').disabled = true;
}
document.getElementById('pgCnt').value = document.getElementById('pgCnt').value - 1;
for(i = 0; i < m;i++)
{
$.ajax({
type: "POST",
url: "getEODRow.php",
data: "page=" + currPage + "&row=" + i,
success: function(html)
{
var row = document.getElementById('chRecommend').insertRow(0);
temp = html.split(",");
for(j = 0; j < 9; j++)
{
str = temp[j].replace("\"","");
str = temp[j].replace("\"",'');
str = temp[j].replace("[",'');
col = row.insertCell(j);
col.innerHTML = str;
}
}
});
}
currPage++;
}
I realize this question is pretty much dead, but I came across it looking for something else, and I figured I'd toss an answer at it. Since it's not a critical issue, I went ahead and reworked everything you've got here plus a lot of code that you didn't choose to include.
// App namespace
var MyApp = {Paging: {}};
// Paging Controller
MyApp.Paging.Controller = function(){ this.init.apply(this,arguments);};
MyApp.Paging.Controller.prototype =
{
// Initializer gets everything hooked up
init: function()
{
$.log("Initializing Paging Controller.")
// Get all the nodes we'll need
this.totCntNode = document.getElementById("totCnt");
this.pgCntNode = document.getElementById("pgCnt");
this.currMinNode = document.getElementById("currMin");
this.currMaxNode = document.getElementById("currMax");
this.prevPageButton = document.getElementById("prevPageButton");
this.nextPageButton = document.getElementById("nextPageButton");
this.pageContainer = document.getElementById("pageOfItems");
// Mimic table's .insertRow to make row adding easy
this.pageContainer.insertRow = function() {
var row = document.createElement("div");
row.className = "row clearfix";
for (var i = 0; i < MyApp.Paging.Model.itemsPerRow; i++)
{
var cell = document.createElement("span");
row.appendChild(cell);
}
this.appendChild(row);
return row;
};
// Attach listeners to the next and previous buttons
this.prevPageButton.onclick = this.showPrevPage.bind(this);
this.nextPageButton.onclick = this.showNextPage.bind(this);
// Update the display for the first time
this.updatePageInfo();
},
// Run this whenever the model has changed and needs to update the display
updatePageInfo: function()
{
// Get info about what page we're on
var currentPage = MyApp.Paging.Model.currentPage,
totalPages = MyApp.Paging.Model.getTotalPages(),
itemCount = MyApp.Paging.Model.itemCount,
pageSize = MyApp.Paging.Model.getPageSize(),
rowsPerPage = MyApp.Paging.Model.rowsPerPage,
rowsOnThisPage = Math.ceil(MyApp.Paging.Model.getItemsOnPage(currentPage)/MyApp.Paging.Model.itemsPerRow);
// Clear out previous page data
while (this.pageContainer.children.length > 0)
{
this.pageContainer.removeChild(this.pageContainer.children[0]);
}
// Add space for the new page data
for (var rowInd = 0; rowInd < rowsOnThisPage ; rowInd++)
{
this.pageContainer.insertRow();
}
$.log("Loading Page " + currentPage + ".");
// Request the data via ajax for each row
for(var i = 0; i < rowsOnThisPage ; i++)
{
$.ajax({
type: MyApp.Paging.Model.queryType,
url: MyApp.Paging.Model.queryURI,
data: MyApp.Paging.Model.getQueryData(currentPage, i),
success: function(pageNum, rowNum, result)
{
// Don't serve data from the wrong page
if (pageNum !== MyApp.Paging.Model.currentPage) return;
// When we get the data back, put it into the correct container
// regardless of when it was received
var row = this.pageContainer.children[rowNum],
temp = result.replace(/[\["]/g,"").split(","),
str = "";
for(var j = 0; j < temp.length; j++)
{
row.children[j].innerHTML = temp[j];
}
}.bind(this, currentPage, i)
});
}
// Update the informational bits under the items
this.totCntNode.textContent = itemCount;
this.pgCntNode.textContent = totalPages;
var min = currentPage * (pageSize ) + 1;
this.currMinNode.textContent = min;
this.currMaxNode.textContent = Math.min(min + pageSize - 1, itemCount);
// Disable the prev page button if there are no previous pages
if (currentPage <= 0)
{
if (this.prevPageButton.className.indexOf("disabled") < 0)
{
this.prevPageButton.className += " disabled";
}
}
// Enable the prev page button if there are previous pages
else
{
if (this.prevPageButton.className.indexOf("disabled") > -1)
{
this.prevPageButton.className = this.prevPageButton.className.replace(/(?:^|\s+)disabled(?!\S)/g, "");
}
}
// Disable the next page button if there are next pages
if (currentPage + 1 >= totalPages)
{
if (this.nextPageButton.className.indexOf("disabled") < 0)
{
this.nextPageButton.className += " disabled";
}
}
// Enable the next page button if there are next pages
else
{
if (this.nextPageButton.className.indexOf("disabled") > -1)
{
this.nextPageButton.className = this.nextPageButton.className.replace(/(?:^|\s+)disabled(?!\S)/g, "");
}
}
},
// This is called when the next page button is clicked.
showNextPage: function()
{
if (MyApp.Paging.Model.currentPage + 1 >= MyApp.Paging.Model.getTotalPages())
{
// Shouldn't have been able to activate this anyway
}
else
{
MyApp.Paging.Model.currentPage++;
this.updatePageInfo();
}
return false;
},
// This is called when the prev page button is clicked
showPrevPage: function()
{
if (MyApp.Paging.Model.currentPage <= 0)
{
// Shouldn't have been able to activate this anyway
}
else
{
MyApp.Paging.Model.currentPage--;
this.updatePageInfo();
}
return false;
}
};
// I typically expect an object like this to be created by the server and dropped dynamically onto the page
MyApp.Paging.Model = {
itemCount: 140,
itemsPerRow: 9,
rowsPerPage: 5,
currentPage: 0,
queryType: "POST",
queryURI: "getEODRow.php",
queryDataFormat: "page={itemPage}&row={itemRow}",
getTotalPages: function() {
with(MyApp.Paging.Model) {
return Math.ceil(itemCount/(itemsPerRow*rowsPerPage));
}
},
getPageSize: function() {
with(MyApp.Paging.Model) {
return itemsPerRow * rowsPerPage;
}
},
getItemsOnPage: function(pageNum) {
with(MyApp.Paging.Model) {
return Math.min(((pageNum+1) * getPageSize()), itemCount) - pageNum*getPageSize();
}
},
getItemsInRow: function(pageNum, rowNum) {
with(MyApp.Paging.Model) {
var onPage = getItemsOnPage(pageNum);
return Math.min((rowNum+1)*itemsPerRow, onPage) - rowNum*itemsPerRow;
}
},
getQueryData: function(itemPage, itemRow) {
with(MyApp.Paging.Model) {
var data = queryDataFormat;
data = data.replace(/{itemPage}/gi, itemPage);
data = data.replace(/{itemRow}/gi, itemRow);
return data;
}
}
};
So, whenever the page is loaded, with an onload handler or whatever, you would create and hang onto a singleton instance of the Paging Controller.
MyApp.Paging.Controller.instance = new MyApp.Paging.Controller();
This should handle issues with Ajax calls returning out of order as well as partial pages of data and partial rows within those pages.
Demo: http://jsfiddle.net/2UJH8/8/
Related
Using a script to sync google sheets with google calendar. It was originally posted on GitHub by DavePar - the original can be seen here - GitHub project
Changed a couple of titles and it works fine.
However, added a column title Stand and getting the following error message. When tried to run the script now
TypeError: Cannot find function getStand in object CalendarEvent.
Have looked through several times and can't see where the problem lies. Can anyone have a look though and point me in the right direction, please?
Here is the slightly modified version:
// Script to synchronize a calendar to a spreadsheet and vice versa.
//
// See https://github.com/Davepar/gcalendarsync for instructions on setting this up.
//
// Set this value to match your calendar!!!
// Calendar ID can be found in the "Calendar Address" section of the Calendar Settings.
var calendarId = 'dtsmike#googlemail.com';
// Set the beginning and end dates that should be synced. beginDate can be set to Date() to use
// today. The numbers are year, month, date, where month is 0 for Jan through 11 for Dec.
var beginDate = new Date(1970, 0, 1); // Default to Jan 1, 1970
var endDate = new Date(2500, 0, 1); // Default to Jan 1, 2500
// Date format to use in the spreadsheet.
var dateFormat = 'd/m/yyyy H:mm';
var titleRowMap = {
'title': 'Title',
'stand': 'Stand',
'description': 'Kit Prep',
'location': 'Location',
'starttime': 'Install',
'endtime': 'Show Finish',
'guests': 'Guests',
'color': 'Color',
'id': 'Id'
};
var titleRowKeys = ['title', 'stand', 'description', 'location', 'starttime', 'endtime', 'guests', 'color', 'id'];
var requiredFields = ['id', 'title', 'starttime', 'endtime'];
// This controls whether email invites are sent to guests when the event is created in the
// calendar. Note that any changes to the event will cause email invites to be resent.
var SEND_EMAIL_INVITES = false;
// Setting this to true will silently skip rows that have a blank start and end time
// instead of popping up an error dialog.
var SKIP_BLANK_ROWS = true;
// Updating too many events in a short time period triggers an error. These values
// were tested for updating 40 events. Modify these values if you're still seeing errors.
var THROTTLE_THRESHOLD = 10;
var THROTTLE_SLEEP_TIME = 75;
// Adds the custom menu to the active spreadsheet.
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [
{
name: "Update from Calendar",
functionName: "syncFromCalendar"
}, {
name: "Update to Calendar",
functionName: "syncToCalendar"
}
];
spreadsheet.addMenu('Calendar Sync', menuEntries);
}
// Creates a mapping array between spreadsheet column and event field name
function createIdxMap(row) {
var idxMap = [];
for (var idx = 0; idx < row.length; idx++) {
var fieldFromHdr = row[idx];
for (var titleKey in titleRowMap) {
if (titleRowMap[titleKey] == fieldFromHdr) {
idxMap.push(titleKey);
break;
}
}
if (idxMap.length <= idx) {
// Header field not in map, so add null
idxMap.push(null);
}
}
return idxMap;
}
// Converts a spreadsheet row into an object containing event-related fields
function reformatEvent(row, idxMap, keysToAdd) {
var reformatted = row.reduce(function(event, value, idx) {
if (idxMap[idx] != null) {
event[idxMap[idx]] = value;
}
return event;
}, {});
for (var k in keysToAdd) {
reformatted[keysToAdd[k]] = '';
}
return reformatted;
}
// Converts a calendar event to a psuedo-sheet event.
function convertCalEvent(calEvent) {
convertedEvent = {
'id': calEvent.getId(),
'title': calEvent.getTitle(),
'stand': calEvent.getStand(),
'description': calEvent.getDescription(),
'location': calEvent.getLocation(),
'guests': calEvent.getGuestList().map(function(x) {return x.getEmail();}).join(','),
'color': calEvent.getColor()
};
if (calEvent.isAllDayEvent()) {
convertedEvent.starttime = calEvent.getAllDayStartDate();
var endtime = calEvent.getAllDayEndDate();
if (endtime - convertedEvent.starttime === 24 * 3600 * 1000) {
convertedEvent.endtime = '';
} else {
convertedEvent.endtime = endtime;
if (endtime.getHours() === 0 && endtime.getMinutes() == 0) {
convertedEvent.endtime.setSeconds(endtime.getSeconds() - 1);
}
}
} else {
convertedEvent.starttime = calEvent.getStartTime();
convertedEvent.endtime = calEvent.getEndTime();
}
return convertedEvent;
}
// Converts calendar event into spreadsheet data row
function calEventToSheet(calEvent, idxMap, dataRow) {
convertedEvent = convertCalEvent(calEvent);
for (var idx = 0; idx < idxMap.length; idx++) {
if (idxMap[idx] !== null) {
dataRow[idx] = convertedEvent[idxMap[idx]];
}
}
}
// Returns empty string or time in milliseconds for Date object
function getEndTime(ev) {
return ev.endtime === '' ? '' : ev.endtime.getTime();
}
// Tests whether calendar event matches spreadsheet event
function eventMatches(cev, sev) {
var convertedCalEvent = convertCalEvent(cev);
return convertedCalEvent.title == sev.title &&
convertedCalEvent.description == sev.description &&
convertedCalEvent.stand == sev.stand &&
convertedCalEvent.location == sev.location &&
convertedCalEvent.starttime.toString() == sev.starttime.toString() &&
getEndTime(convertedCalEvent) === getEndTime(sev) &&
convertedCalEvent.guests == sev.guests &&
convertedCalEvent.color == ('' + sev.color);
}
// Determine whether required fields are missing
function areRequiredFieldsMissing(idxMap) {
return requiredFields.some(function(val) {
return idxMap.indexOf(val) < 0;
});
}
// Returns list of fields that aren't in spreadsheet
function missingFields(idxMap) {
return titleRowKeys.filter(function(val) {
return idxMap.indexOf(val) < 0;
});
}
// Set up formats and hide ID column for empty spreadsheet
function setUpSheet(sheet, fieldKeys) {
sheet.getRange(1, fieldKeys.indexOf('starttime') + 1, 999).setNumberFormat(dateFormat);
sheet.getRange(1, fieldKeys.indexOf('endtime') + 1, 999).setNumberFormat(dateFormat);
sheet.hideColumns(fieldKeys.indexOf('id') + 1);
}
// Display error alert
function errorAlert(msg, evt, ridx) {
var ui = SpreadsheetApp.getUi();
if (evt) {
ui.alert('Skipping row: ' + msg + ' in event "' + evt.title + '", row ' + (ridx + 1));
} else {
ui.alert(msg);
}
}
// Updates a calendar event from a sheet event.
function updateEvent(calEvent, sheetEvent){
sheetEvent.sendInvites = SEND_EMAIL_INVITES;
if (sheetEvent.endtime === '') {
calEvent.setAllDayDate(sheetEvent.starttime);
} else {
calEvent.setTime(sheetEvent.starttime, sheetEvent.endtime);
}
calEvent.setTitle(sheetEvent.title);
calEvent.setDescription(sheetEvent.description);
calEvent.setStand(sheetEvent.stand);
calEvent.setLocation(sheetEvent.location);
// Set event color
if (sheetEvent.color > 0 && sheetEvent.color < 12) {
calEvent.setColor('' + sheetEvent.color);
}
var guestCal = calEvent.getGuestList().map(function (x) {
return {
email: x.getEmail(),
added: false
};
});
var sheetGuests = sheetEvent.guests || '';
var guests = sheetGuests.split(',').map(function (x) {
return x ? x.trim() : '';
});
// Check guests that are already invited.
for (var gIx = 0; gIx < guestCal.length; gIx++) {
var index = guests.indexOf(guestCal[gIx].email);
if (index >= 0) {
guestCal[gIx].added = true;
guests.splice(index, 1);
}
}
guests.forEach(function (x) {
if (x) calEvent.addGuest(x);
});
guestCal.forEach(function (x) {
if (!x.added) {
calEvent.removeGuest(x.email);
}
});
}
// Synchronize from calendar to spreadsheet.
function syncFromCalendar() {
// Get calendar and events
var calendar = CalendarApp.getCalendarById(calendarId);
var calEvents = calendar.getEvents(beginDate, endDate);
// Get spreadsheet and data
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var range = sheet.getDataRange();
var data = range.getValues();
var eventFound = new Array(data.length);
// Check if spreadsheet is empty and add a title row
var titleRow = [];
for (var idx = 0; idx < titleRowKeys.length; idx++) {
titleRow.push(titleRowMap[titleRowKeys[idx]]);
}
if (data.length < 1) {
data.push(titleRow);
range = sheet.getRange(1, 1, data.length, data[0].length);
range.setValues(data);
setUpSheet(sheet, titleRowKeys);
}
if (data.length == 1 && data[0].length == 1 && data[0][0] === '') {
data[0] = titleRow;
range = sheet.getRange(1, 1, data.length, data[0].length);
range.setValues(data);
setUpSheet(sheet, titleRowKeys);
}
// Map spreadsheet headers to indices
var idxMap = createIdxMap(data[0]);
var idIdx = idxMap.indexOf('id');
// Verify header has all required fields
if (areRequiredFieldsMissing(idxMap)) {
var reqFieldNames = requiredFields.map(function(x) {return titleRowMap[x];}).join(', ');
errorAlert('Spreadsheet must have ' + reqFieldNames + ' columns');
return;
}
// Array of IDs in the spreadsheet
var sheetEventIds = data.slice(1).map(function(row) {return row[idIdx];});
// Loop through calendar events
for (var cidx = 0; cidx < calEvents.length; cidx++) {
var calEvent = calEvents[cidx];
var calEventId = calEvent.getId();
var ridx = sheetEventIds.indexOf(calEventId) + 1;
if (ridx < 1) {
// Event not found, create it
ridx = data.length;
var newRow = [];
var rowSize = idxMap.length;
while (rowSize--) newRow.push('');
data.push(newRow);
} else {
eventFound[ridx] = true;
}
// Update event in spreadsheet data
calEventToSheet(calEvent, idxMap, data[ridx]);
}
// Remove any data rows not found in the calendar
var rowsDeleted = 0;
for (var idx = eventFound.length - 1; idx > 0; idx--) {
//event doesn't exists and has an event id
if (!eventFound[idx] && sheetEventIds[idx - 1]) {
data.splice(idx, 1);
rowsDeleted++;
}
}
// Save spreadsheet changes
range = sheet.getRange(1, 1, data.length, data[0].length);
range.setValues(data);
if (rowsDeleted > 0) {
sheet.deleteRows(data.length + 1, rowsDeleted);
}
}
// Synchronize from spreadsheet to calendar.
function syncToCalendar() {
// Get calendar and events
var calendar = CalendarApp.getCalendarById(calendarId);
if (!calendar) {
errorAlert('Cannot find calendar. Check instructions for set up.');
}
var calEvents = calendar.getEvents(beginDate, endDate);
var calEventIds = calEvents.map(function(val) {return val.getId();});
// Get spreadsheet and data
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var range = sheet.getDataRange();
var data = range.getValues();
if (data.length < 2) {
errorAlert('Spreadsheet must have a title row and at least one data row');
return;
}
// Map headers to indices
var idxMap = createIdxMap(data[0]);
var idIdx = idxMap.indexOf('id');
var idRange = range.offset(0, idIdx, data.length, 1);
var idData = idRange.getValues()
// Verify header has all required fields
if (areRequiredFieldsMissing(idxMap)) {
var reqFieldNames = requiredFields.map(function(x) {return titleRowMap[x];}).join(', ');
errorAlert('Spreadsheet must have ' + reqFieldNames + ' columns');
return;
}
var keysToAdd = missingFields(idxMap);
// Loop through spreadsheet rows
var numChanges = 0;
var numUpdated = 0;
var changesMade = false;
for (var ridx = 1; ridx < data.length; ridx++) {
var sheetEvent = reformatEvent(data[ridx], idxMap, keysToAdd);
// If enabled, skip rows with blank/invalid start and end times
if (SKIP_BLANK_ROWS && !(sheetEvent.starttime instanceof Date) &&
!(sheetEvent.endtime instanceof Date)) {
continue;
}
// Do some error checking first
if (!sheetEvent.title) {
errorAlert('must have title', sheetEvent, ridx);
continue;
}
if (!(sheetEvent.starttime instanceof Date)) {
errorAlert('start time must be a date/time', sheetEvent, ridx);
continue;
}
if (sheetEvent.endtime !== '') {
if (!(sheetEvent.endtime instanceof Date)) {
errorAlert('end time must be empty or a date/time', sheetEvent, ridx);
continue;
}
if (sheetEvent.endtime < sheetEvent.starttime) {
errorAlert('end time must be after start time for event', sheetEvent, ridx);
continue;
}
}
// Ignore events outside of the begin/end range desired.
if (sheetEvent.starttime > endDate) {
continue;
}
if (sheetEvent.endtime === '') {
if (sheetEvent.starttime < beginDate) {
continue;
}
} else {
if (sheetEvent.endtime < beginDate) {
continue;
}
}
// Determine if spreadsheet event is already in calendar and matches
var addEvent = true;
if (sheetEvent.id) {
var eventIdx = calEventIds.indexOf(sheetEvent.id);
if (eventIdx >= 0) {
calEventIds[eventIdx] = null; // Prevents removing event below
addEvent = false;
var calEvent = calEvents[eventIdx];
if (!eventMatches(calEvent, sheetEvent)) {
// Update the event
updateEvent(calEvent, sheetEvent);
// Maybe throttle updates.
numChanges++;
if (numChanges > THROTTLE_THRESHOLD) {
Utilities.sleep(THROTTLE_SLEEP_TIME);
}
}
}
}
if (addEvent) {
var newEvent;
sheetEvent.sendInvites = SEND_EMAIL_INVITES;
if (sheetEvent.endtime === '') {
newEvent = calendar.createAllDayEvent(sheetEvent.title, sheetEvent.starttime, sheetEvent);
} else {
newEvent = calendar.createEvent(sheetEvent.title, sheetEvent.starttime, sheetEvent.endtime, sheetEvent);
}
// Put event ID back into spreadsheet
idData[ridx][0] = newEvent.getId();
changesMade = true;
// Set event color
if (sheetEvent.color > 0 && sheetEvent.color < 12) {
newEvent.setColor('' + sheetEvent.color);
}
// Maybe throttle updates.
numChanges++;
if (numChanges > THROTTLE_THRESHOLD) {
Utilities.sleep(THROTTLE_SLEEP_TIME);
}
}
}
// Save spreadsheet changes
if (changesMade) {
idRange.setValues(idData);
}
// Remove any calendar events not found in the spreadsheet
var numToRemove = calEventIds.reduce(function(prevVal, curVal) {
if (curVal !== null) {
prevVal++;
}
return prevVal;
}, 0);
if (numToRemove > 0) {
var ui = SpreadsheetApp.getUi();
var response = ui.Button.YES;
if (numToRemove > numUpdated) {
response = ui.alert('Delete ' + numToRemove + ' calendar event(s) not found in spreadsheet?',
ui.ButtonSet.YES_NO);
}
if (response == ui.Button.YES) {
calEventIds.forEach(function(id, idx) {
if (id != null) {
calEvents[idx].deleteEvent();
Utilities.sleep(20);
}
});
}
}
Logger.log('Updated %s calendar events', numChanges);
}
// Set up a trigger to automatically update the calendar when the spreadsheet is
// modified. See the instructions for how to use this.
function createSpreadsheetEditTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger('syncToCalendar')
.forSpreadsheet(ss)
.onEdit()
.create();
}
// Delete the trigger. Use this to stop automatically updating the calendar.
function deleteTrigger() {
// Loop over all triggers.
var allTriggers = ScriptApp.getProjectTriggers();
for (var idx = 0; idx < allTriggers.length; idx++) {
if (allTriggers[idx].getHandlerFunction() === 'syncToCalendar') {
ScriptApp.deleteTrigger(allTriggers[idx]);
}
}
}
DEMO
I'am developing a Pagination Functionality using handlebars js and fetching the data from JSON.
First 5 results will be shown on page load.
on click of next pagination another set of 5 results will be displayed and so on.
If i have total number of results 100 by displaying each 5 Results in page. Page Numbers will be 1 of 20.
if the pagination has more then 5 number of Pages , I want to display "1,2,3 ... last Page Number (20)" same vice versa
on load Previous Button Should be hidden when ever next page is clicked it has to be enabled.
Request to you please look into this and give some advice / suggestion on this.
Should be Like Below
Appreciate your kind help !
Thanks
some code sample :
$(function () {
var opts = {
pageMax: 5,
postsDiv: $('#posts'),
dataUrl: "searchResult.json"
}
function range(i) { return i ? range(i - 1).concat(i) : [] }
function loadPosts(posts) {
opts.postsDiv.empty();
posts.each(function () {
var source = $("#post-template").html();
var template = Handlebars.compile(source);
var context = {
title: this.title,
desc: this.body,
};
var html = template(context);
opts.postsDiv.append(html);
});
}
function paginate(pageCount) {
var source = $("#pagination-template").html();
var template = Handlebars.compile(source);
var context = { pages: range(pageCount) };
var html = template(context);
opts.postsDiv.after(html);
function changePage(pageNumber) {
pageItems.removeClass('active');
pageItems.filter('[data-page="' + pageNumber + '"]').addClass('active');
loadPosts(data.slice(pageNumber * opts.pageMax - opts.pageMax, pageNumber * opts.pageMax));
}
var pageItems = $('.pagination>li.pagination-page');
pageItems.on('click', function () {
changePage(this.getAttribute('data-page'));
}).filter('[data-page="1"]').addClass('active');
$('.pagination>li.pagination-prev').on('click', function () {
gotoPageNumber = parseInt($('.pagination>li.active').attr('data-page')) - 1;
if (gotoPageNumber <= 0) { gotoPageNumber = pageCount; }
changePage(gotoPageNumber);
});
$('.pagination>li.pagination-next').on('click', function () {
gotoPageNumber = parseInt($('.pagination>li.active').attr('data-page')) + 1;
if (gotoPageNumber > pageCount) { gotoPageNumber = 1; }
changePage(gotoPageNumber);
});
}
$.ajax({
dataType: 'json',
url: opts.dataUrl,
success: function (response_json) {
data = $(response_json.records.page);
dataCount = data.length;
pageCount = Math.ceil(dataCount / opts.pageMax);
if (dataCount > opts.pageMax) {
paginate(pageCount);
posts = data.slice(0, opts.pageMax);
} else {
posts = data;
}
loadPosts(posts);
}
});
});
I had to solve a similar issue a few months ago. I found this Gist from kottenator.
Your range function is modified thusly, with c being the current page, and m your pageCount. Calls to the function have been modified a bit and a recursive call to your paginate(...) function is also added to recompute the tag after navigation (also, a branch was added to your DOM appending function calls, to modify the pagination tag, I used a ternary operator. There may be more elegant to achieve this).
See this CodePen
function range(c,m) {
var current = c || 1,
last = m,
delta = 2,
left = current - delta,
right = parseInt(current) + delta + 1,
range = [],
rangeWithEllipsis = [],
l,
t;
range.push(1);
for (var i = c - delta ; i <= c + delta ; i++) {
if (i >= left && i < right && i < m && i > 1) {
range.push(i);
}
}
range.push(m);
for (var i of range) {
if (l) {
if (i - l === 2) {
t = l+1;
rangeWithEllipsis.push(t);
} else if (i - l !== 1) {
rangeWithEllipsis.push("...");
}
}
rangeWithEllipsis.push(i);
l = i;
}
return rangeWithEllipsis;
}
It doesn't solve exactly your problem per say, but it does paginate correctly.
If I have some time, I'll try and make it paginate the exact way you want to (it's really only about customizing the delta, left and right operand in the algorithm, and changing your pagination next and pagination prev event handler calls).
Edit I changed the algorithm to find the left and right boundary. Your index.html is also modified a bit.
The idea is to compute the left and right boundary by multiples of 5. You then create a range of the indexes to show and add an elipsis if the difference is too big. This should effectively solves your original problem.
JavaScript
getFirstDigits = (t) => {
return parseInt(t.toString().slice(0,-1))
}
getLastDigit = (t) => {
return parseInt(t.toString().slice(-1))
}
isMultipleOf5 = (t) => {
return [0,5].reduce((res,curr)=>{
return res = res || curr === getLastDigit(t);
},false);
}
isBetween0and5 = (t) => {
const _t = getLastDigit(t);
return _t < 5;
}
isBetween5and9 = (t) => {
const _t = getLastDigit(t);
return _t => 5 && _t <= 9;
}
appendDigit = (t,d) => {
return parseInt(getFirstDigits(t).toString() + d.toString())
}
getSecondRightMostDigit = (t) => {
return parseInt(t.toString().slice(-2,-1))
}
incrementSecondDigit = (t) => {
return t+10;
}
getLeft = (t) => {
if(t>=10){
if(isBetween0and5(t)) return appendDigit(t,0);
else return appendDigit(t,5);
} else {
if (t<5) return 0;
else return 5;
}
}
getRight = (t) => {
if(t<5) return 5;
else if (t<10) return 10;
else if(isBetween0and5(t)) return appendDigit(t,5)
else return appendDigit(incrementSecondDigit(t),0);
}
function range(c,m) {
var current = c || 1,
last = m,
delta = 2,
left = getLeft(c),
right = getRight(c),
range = [],
rangeWithEllipsis = [],
l,
t;
var rightBoundary = right < 5 ? 5 : right;
for (var i = left ; i < rightBoundary ; ++i) {
if( i < m && i > 0) range.push(i);
}
range.push(m);
for (var i of range) {
if (l) {
if (i - l === 2) {
t = l+1;
rangeWithEllipsis.push(t);
} else if (i - l !== 1){
rangeWithEllipsis.push("...");
}
}
rangeWithEllipsis.push(i);
l = i;
}
return rangeWithEllipsis;
}
HTML/HandleBars
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Handlebars Pagination</title>
<link href="main.css" rel="stylesheet" />
<script src="jquery.min.js"></script>
<script src="handlebars.min.js"></script>
<script src="functions.js"></script>
</head>
<body class="container">
<div id="posts"></div>
<script id="pagination-template" type="text/x-handlebars-template">
<ul class="pagination">
<li class="pagination-prev">«</li>
{{#each pages}}
<li class="pagination-page" data-page="{{this}}">{{this}}</li>
{{/each}}
<li class="pagination-next">»</li>
</ul>
</script>
<script id="post-template" type="text/x-handlebars-template">
<div class="score-structural score-column2-wideright search-listings post">
<div class="score-right">
<h4>{{record_count}}</h4>
<h5 style="z-index: 1;">
{{ title }}
</h5>
<p style="z-index: 1;"> {{ desc }} </p>
</div>
</div>
<hr>
</script>
</body>
</html>
<script>
$(function () {
var opts = {
pageMax: 2,
postsDiv: $('#posts'),
dataUrl: "searchResult.json"
}
function loadPosts(posts) {
opts.postsDiv.empty();
posts.each(function () {
var source = $("#post-template").html();
var template = Handlebars.compile(source);
var context = {
title: this.title,
desc: this.body,
};
var html = template(context);
opts.postsDiv.append(html);
});
hidePrev();
}
function hidePrev() { $('.pagination .pagination-prev').hide(); }
function showPrev() { $('.pagination .pagination-prev').show(); }
function hideNext() { $('.pagination .pagination-next').hide(); }
function showNext() { $('.pagination .pagination-next').show(); }
function paginate(page,pageCount) {
var source = $("#pagination-template").html();
var template = Handlebars.compile(source);
var context = { pages: range(page,pageCount) };
console.log(range(page,pageCount));
var html = template(context);
var paginationTag = opts.postsDiv.parent().find(".pagination");
paginationTag.length > 0 ? paginationTag.replaceWith(html) : opts.postsDiv.before(html);
function changePage(page) {
pageItems.removeClass('active');
pageItems.filter('[data-page="' + page + '"]').addClass('active');
loadPosts(data.slice(page * opts.pageMax - opts.pageMax, page * opts.pageMax));
paginate(page,pageCount);
if (gotoPageNumber <= 1) {
hidePrev();
}
}
var pageItems = $('.pagination>li.pagination-page');
var pageItemsLastPage = $('.pagination li').length - 2;
pageItems.removeClass('active');
pageItems.filter('[data-page="' + page + '"]').addClass('active');
pageItems.on('click', function () {
getDataPageNo = this.getAttribute('data-page')
console.log(getDataPageNo)
changePage(getDataPageNo);
if (getDataPageNo == 1) {
hidePrev()
}
else if (getDataPageNo == pageItemsLastPage) {
hideNext();
}
else {
showPrev();
showNext();
}
});
$('.pagination>li.pagination-prev').on('click', function () {
gotoPageNumber = parseInt($('.pagination>li.active').attr('data-page')) - 1;
changePage(gotoPageNumber);
});
$('.pagination>li.pagination-next').on('click', function () {
gotoPageNumber = parseInt($('.pagination>li.active').attr('data-page')) + 1;
if (gotoPageNumber > pageCount) {
gotoPageNumber = 1;
showPrev();
}
changePage(gotoPageNumber);
});
}
$.ajax({
dataType: 'json',
url: opts.dataUrl,
success: function (response_json) {
data = $(response_json.records.page);
dataCount = data.length;
pageCount = Math.ceil(dataCount / opts.pageMax);
if (dataCount > opts.pageMax) {
paginate(1,pageCount);
posts = data.slice(0, opts.pageMax);
} else {
posts = data;
}
loadPosts(posts);
}
});
});
</script>
Here is the page where I'm trying to display content. It's showing up blank. My application is a single page application, so most of the code is in the index.html file
verbPractice.html
<div>
<h1>Practice verbs here</h1>
<div class="row" ng-repeat="sentence in listOfSentences">
<div class="col-xs-12">
<p>{{sentence.first}} {{sentence.second}} {{sentence.third}}</p>
</div>
</div>
</div>
This page is linked to from another page called verbSelect.html. Here is the relevant code from that page
<div class="btn btn-primary" ui-sref="app.verbPractice" ng-click="storeInfo(); generateSentences()">Submit</div>
Both the above pages are under the same controller called verbController:
(function() {
'use strict';
angular.module('arabicApp')
.controller('verbController', ['$scope', 'verbFactory', 'pronounFactory', 'attachedFactory', function($scope, verbFactory, pronounFactory, attachedFactory){
//Gets verbs from server
$scope.verbArray = verbFactory.getVerbs().query(
function(response) {
$scope.verbArray = response;
}
);
//Gets pronouns from server
$scope.pronouns = pronounFactory.getPronouns().query(
function(response) {
$scope.pronouns = response;
}
);
$scope.attached = attachedFactory.getAttached().query(
function(response) {
$scope.attached = response;
}
);
//Stores the array of selected verbs
$scope.selectedVerbs = [];
$scope.numSelectedVerbs = 0;
//Searches theArray for name and returns its index. If not found, returns -1
$scope.searchArray = function(theArray, name) {
for (var i = 0; i < theArray.length; i++) {
if (theArray[i].name === name) {
return i;
}
}
return -1;
};
//Adds verbs to selected list
$scope.addToSelected = function(theVerb) {
var num = $scope.searchArray($scope.selectedVerbs, theVerb.name);
var divToChange = document.getElementById("verbSelect_"+theVerb.name);
if (num > -1) { //Found. Remeove it from selectedVerbs
$scope.selectedVerbs.splice(num, 1);
divToChange.className = divToChange.className.replace( /(?:^|\s)listItemActive(?!\S)/g , '' );
$scope.numSelectedVerbs = $scope.numSelectedVerbs - 1;
} else { //Not found. Add it in
$scope.selectedVerbs.push(theVerb);
divToChange.className += " listItemActive";
$scope.numSelectedVerbs = $scope.numSelectedVerbs + 1;
}
};
//Stores how many practice questions the user wants
$scope.howMany = 0;
//Stores what tense of verbs the user wants
$scope.verbTense = "Both";
//Stores what form the user wants
$scope.verbVoice = "Both";
//Include commands?
$scope.includeCommands = false;
//Sentense that will be generated
$scope.listOfSentences = [];
$scope.generateSentence = function(isCommand, theTense, theVoice) {
var sent = {"first": "", "second": "", "third": ""};
var attachedPicker = Math.floor(Math.random()*14);
var attachedToUse = $scope.attached[attachedPicker].attached;
var pronounPicker = Math.floor(Math.random()*14);
var pronounToUse = $scope.pronouns[pronounPicker].pronoun;
sent.first = pronounToUse;
var verbPicker = Math.floor(Math.random()*$scope.numSelectedVerbs);
var verbToUse = $scope.selectedVerbs[verbPicker][theTense][pronounToUse];
if (isCommand === true) {
sent.second = verbToUse;
} else {
if (theVoice === "Passive") {
if (theTense === "Past") { sent.second = "were"; }
else { sent.second = "are"; }
sent.third = verbToUse;
} else {
sent.second = verbToUse;
sent.third = attachedToUse;
}
}
return sent;
};
$scope.storeInfo = function() {
localStorage.setItem("howMany", $scope.howMany);
localStorage.setItem("verbTense", $scope.verbTense);
localStorage.setItem("verbVoice", $scope.verbVoice);
localStorage.setItem("includeCommands", $scope.includeCommands);
};
$scope.getStoredInfo = function() {
$scope.howMany = localStorage.getItem("howMany");
$scope.verbTense = localStorage.getItem("verbTense");
$scope.verbVoice = localStorage.getItem("verbVoice");
$scope.includeCommands = localStorage.getItem("includeCommands");
};
//Generates sentences using the variables from verbSelect
$scope.generateSentences = function() {
$scope.getStoredInfo();
var tensePicker;
var voicePicker;
var doCommand;
var rand;
for (var i = 0; i < $scope.howMany; i++) {
//Picks the verb tense
if ($scope.verbTense === "Both") {
rand = Math.floor(Math.random());
if (rand === 0) { tensePicker = "Past"; }
else { tensePicker = "Present"; }
} else {
tensePicker = $scope.verbTense;
}
//Picks the verb voice
if ($scope.verbVoice === "Both") {
rand = Math.floor(Math.random());
if (rand === 0) { voicePicker = "Active"; }
else { voicePicker = "Passive"; }
} else {
voicePicker = $scope.verbVoice;
}
//If the voice is passive, use past tense
if ($scope.verbVoice === "Passive") { tensePicker = "Past"; }
//Determines if the sentence will be a command sentence or not
if ($scope.includeCommands === true) {
rand = Math.floor(Math.random() * 6);
if (rand === 0) { doCommand = true; }
else { doCommand = false; }
} else {
doCommand = false;
}
var sentence = $scope.generateSentence(doCommand, tensePicker, voicePicker);
$scope.listOfSentences.push(sentence);
}
console.log($scope.listOfSentences);
};
}])
;
})();
The variables: howMany, verbTense, verbVoice, isCommand, are set on this verbSelect.html page using ng-model. Both the verbSelect.html page and verbPractice.html page are under the same controller.
Everything seems to be working fine. At the end of my generateSentences() function, I output $scope.listOfSentences to the log, and it shows up without any problems, the array is being populated just fine. However, in my verbPractice.html page, nothing is showing up except the <h1> heading. For some reason, even though the $scope.listOfSentences array is populated, ng-repeat doesn't seem to be looping. Does anyone have any idea why?
Sorry for the long post
Thanks for taking the time to read and answer this question!
I am trying to add pagination in Angular js.Sinch my server returns huge number of rows on each query So i am using some limit offset to get only 101 rows(required rows+1) at a time.(Building array of 20 pages ,reusing extra row value for next request.)
No- of rows per page=5
So on getting 101 rows means i can paginate upto 20 pages. Since i already have an extra row So i know there is more data left , So on next page request again am querying to get rows 101-201. But my doubt here is how to add logic in next page and previous page function and how to build next or previous set of data?
My app.js-
My 1st time request-
$scope.startingid = null;
$scope.numberofrows= 101;
Api.customer.query({ productId : $scope.customer , productperiod :$scope.customerPeriod,startingid:$scope.startingid,numberofrows:$scope.numberofrows }).$promise.then(function(result) {
if(result){
if(result&&result.length==0){
$scope.addErrorAlert("No Customer data found with this productId and Period.", true);
$scope.displayPage = 'search';
return;
}
$scope.customerResult = result;
$scope.displayPage = 'drill';
$scope.showData();
}
// Pagination Logic-
My code is working fine if result set is small number of data. But need to implement in such a way that it can handle large number of rows as well.
few doubts-
1. how to build the data for request 101-201.
2. next and previous page logic
$scope.paged = function (valLists,itemsPerPage)
{
var retVal = [];
for (var i = 0; i < valLists.length; i++) {
if (i % itemsPerPage === 0) {
retVal[Math.floor(i / itemsPerPage)] = [valLists[i]];
} else {
retVal[Math.floor(i / itemsPerPage)].push(valLists[i]);
}
}
return retVal;
};
$scope.pagination = function () {
$scope.ItemsByPage = $scope.paged( $scope.customerResult, $scope.itemsPerPage );
};
$scope.showData = function( ){
// $scope.noOfrows = 101;
$scope.itemsPerPage = 5;
$scope.currentPage = 0;
$scope.pagination();
$scope.range = function() {
var rangeSize = 4;
var ps = [];
var start;
start = $scope.currentPage;
if ( start > $scope.pageCount()-rangeSize ) {
start = $scope.pageCount()-rangeSize+1;
}
for (var i=start; i<start+rangeSize; i++) {
ps.push(i);
}
return ps;
};
$scope.prevPage = function() {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.DisablePrevPage = function() {
return $scope.currentPage === 0 ? "disabled" : "";
//?? TODO add logic for samething as disabled next page and build table data
};
$scope.pageCount = function() {
return Math.ceil($scope.customerResult.length/$scope.itemsPerPage)-1;
};
$scope.nextPage = function() {
if ($scope.currentPage < $scope.pageCount()) {
$scope.currentPage++;
}
};
$scope.DisableNextPage = function() {
if($scope.currentPage === $scope.pageCount()){
if($scope.noOfrows >$scope.customerResult.length)
return $scope.currentPage === $scope.pageCount() ? "disabled" : "";
$scope.noOfrows = $scope.noOfrows+ 100;
Api.customerReq.query({ productId : $scope.customerProduct , productperiod :$scope.customerPeriod, noOfrows:$scope.noOfrows }).$promise.then(function(result) {
if(result){
if(result&&result.length==0){
return $scope.currentPage === $scope.pageCount() ? "disabled" : "";
}
$scope.showData();// how to build all data on when i query for 101-201 data?
}
});
}
};
$scope.setPage = function(n) {
$scope.currentPage = n;
};
};
I'm trying to write a function that takes a large array and iterates up and down it in a set number of chunks via a previous and next button. I have the next button working fine but cannot get it to reverse the array the same way I go forward. Here's what I have:
Javscript
success: function(data) {
var body = data;
console.log(body.length);
//body/data is a string
var text = body.split(' ');
text.chunk = 0; text.chunkSize = 15;
var next = true;
var increment = function(array,next) {
if (array.chunk < array.length) {
var slice = array.slice(
array.chunk,
Math.min(array.chunk + array.chunkSize, array.length));
var chunk = slice.join(" ");
if (next) {
array.chunk += array.chunkSize;
$( '#test' ).html('<p>' + chunk + '</p>');
}
else {
var slice = array.slice(
array.chunk,
Math.min(array.chunk+array.chunkSize, array.length));
array.chunk -= array.chunkSize;
$( '#test' ).html(chunk);
}
}
}
$("#prev").click(function() {
increment(text);
});
$("#button").click(function() {
increment(text, next);
});
}
success: function(data) {
var body = data;
console.log(body.length);
//body/data is a string
var text = body.split(' ');
text.chunk = 0; text.chunkSize = 15;
var increment = function(array,next) {
if(next) {
array.chunk = Math.min(array.chunk + array.chunkSize, array.length);
} else {
array.chunk = Math.max(array.chunk - array.chunkSize, 0);
}
var slice = array.slice(
array.chunk,
Math.min(array.chunk + array.chunkSize, array.length));
var chunk = slice.join(" ");
}
$("#prev").click(increment(text,false));
$("#button").click(increment(text, true));
}
Is this what you need? Fastly coded, and without testing so use with caution.
Okay, so first of all I really suggest breaking up your code. It looks like this is a response back from a server. I would in the response from the server, parse the data just like you are (side note, why don't you just return json from the server?) but use a call back to handle pagination.
var returnData = data.split(' ');
addPagination(returnData);
Under addPagination I would handle the DOM manipulation:
function addPagination(array) {
$('#container').show();
var incremental = incrementArray(array);
var responseSpan = $('#response');
$('#previous').click(function() {
incremental.previous();
showText();
});
$('#next').click(function() {
incremental.next();
showText();
});
showText();
function showText() {
responseSpan.text(incremental.array.join(', '));
}
}
But to handle the actual shifting of the array, I would use some function outside of your own. This uses Object Oriented JavaScript, so it is a bit more complex. It stores the original array in memory, and has 2 methods (next, previous), and has 1 attribute (array):
function incrementArray(array) {
_increment = 2;
var increment = _increment < array.length ? _increment : array.length;
var index = -2;
this.next = function () {
var isTopOfArray = index + increment > array.length - increment;
index = isTopOfArray ? array.length - increment : index + increment;
this.array = array.slice(index, index + increment);
return this.array;
};
this.previous = function () {
var isBottomOfArray = index - increment < 0;
index = isBottomOfArray ? 0 : index - increment;
this.array = array.slice(index, index + increment);
return this.array;
};
this.next();
return this;
}
To test it, use this jsFiddle.