I'm trying to put pagination function into my table and taking this post "Simple pagination in javascript" for reference.
https://codepen.io/duongvu/pen/eewdPG?editors=1111
It's supposed to input the data from my array into the table's class. However it doesn't work in my case.
It freezes and can not proceed when clicking on <next>
Try this out #Duong Vu
for (var i = 0; i < records_per_page; i++)
{
col[i].innerText = content[i + (page-1) * records_per_page].number;
}
function changePage(page) {
var btn_next = document.getElementById("btn_next");
var btn_prev = document.getElementById("btn_prev");
var col = document.getElementsByClassName("no");
var colName = document.getElementsByClassName("name");
var colDetails = document.getElementsByClassName("info");
var page_span = document.getElementById("page");
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
for (var i = (page - 1) * records_per_page; i < (page * records_per_page); i++) {
col[i % records_per_page].innerText = content[i] ? content[i].number : '';
colName[i % records_per_page].innerText = content[i] ? content[i].name : '';
colDetails[i % records_per_page].innerText = content[i] ? content[i].detail : '';
}
}
You are printing only numbers thats why it was not printing any other result. And as you have only 4 rows, so you need to use col[i % records_per_page] to print inside the table data on page changes.
Here is updated codepen.
Related
Having a mare with this one...
I have a function, which displays pagination ( 1, 2, 3 etc) buttons, for each page of my todo app results.
Specifically for example, if you click on button 2, you'll see page 2 of the results. Here's the full function and the buttons are being inserted via template literals:
// CREATE BUTTONS FOR EACH PAGE THAT EXISTS
function displayNumberedButtons(bookMarksArray) {
for (let x = 0; x < bookMarksArray.length; x++)
listArray.push(x);
numberOfPages = Math.ceil(listArray.length / numberPerPage);
let individualPagesArray = [];
for (var i = 1; i <= numberOfPages; i++) {
individualPagesArray.push(i);
}
// BUTTONS ARE ADDED HERE
for (var i = 0; i < individualPagesArray.length; i++) {
document.getElementById("numbers").innerHTML += `<button onclick=showCurrentPage(${i+1})>` + individualPagesArray[i] + `</button>`;
}
}
However, my onclick function, does not seem to register in my JavaScript:
// PAGINGATION CTAS
window.showCurrentPage = (i) => {
currentPage = i;
paginationCountLogic(bookMarksArray);
}
If I click on any button, I get the following error. And I have no idea why, as I can see the buttons in my DOM.
index.html:1 Uncaught ReferenceError: showCurrentPage is not defined
at HTMLButtonElement.onclick (index.html:1)
This only happens when I compiled my JS files in advanced mode, using google closure compiler. Otherwise, this works fine if the files are not compiled.
Not sure how to resolve this.
Here is the full order the code appears as in my script:
function Pagination() {
let listArray = new Array(); //store the collection of data to be sorted.
let pageList = new Array(); //keep track of the items to display on the current page only
const numberPerPage = 3;
let currentPage = 1; //keep track of where we are in the pagination
let numberOfPages = 1; // calculates the total number of pages
const list = document.querySelector('.url-list');
let nextButton = document.getElementById("next");
const previousButton = document.getElementById("previous");
let bookMarksArray = window.localStorage.getItem('bookMarksArray') ? JSON.parse(window.localStorage.getItem('bookMarksArray')) : [];
// CREATE BUTTONS FOR EACH PAGE THAT EXISTS
function displayNumberedButtons(bookMarksArray) {
for (let x = 0; x < bookMarksArray.length; x++)
listArray.push(x);
numberOfPages = Math.ceil(listArray.length / numberPerPage);
let individualPagesArray = [];
for (var i = 1; i <= numberOfPages; i++) {
individualPagesArray.push(i);
}
for (var i = 0; i < individualPagesArray.length; i++) {
document.getElementById("numbers").innerHTML += `<button id="${i+1}" onclick=showCurrentPage(${i+1})>` + individualPagesArray[i] + `</button>`;
}
}
// CALCULATE WHEN PAGINATION SHOULD BEGIN AND STOP
function paginationCountLogic(bookMarksArray) {
let begin = ((currentPage - 1) * numberPerPage);
let end = begin + numberPerPage;
pageList = bookMarksArray.slice(begin, end);
nextButton.disabled = currentPage === numberOfPages ? true : false;
previousButton.disabled = currentPage === 1 ? true : false;
displayBookmarks(pageList);
}
// DISPLAY BOOKMARKS
function displayBookmarks(pageList) {
list.innerHTML = "";
for (let r = 0; r < pageList.length; r++) {
list.innerHTML +=
`<div>
<form class="text animated slideInDown bookmarksForm" id=${pageList[r].name}>
<input class="nameItem" type="text" name="name" value=${pageList[r].name} id="name" placeholder="Name">
<input class="urlItem" type="url" name="url" value=${pageList[r].url} id="url" placeholder="https://example.com">
<button type="button" class="js-edit-url" id="edit">edit</button>
<button type="button" class="js-delete-url" id="delete">delete</button>
</form>
</div>`;
}
}
// PAGINGATION CTAS
window.showCurrentPage = (i) => {
currentPage = i;
paginationCountLogic(bookMarksArray);
}
window.nextPage = () => {
currentPage += 1;
paginationCountLogic(bookMarksArray);
}
window.previousPage = () => {
currentPage -= 1;
paginationCountLogic(bookMarksArray);
}
return {
displayNumberedButtons,
displayBookmarks,
paginationCountLogic
};
}
The cause is probably that the compiler doesn't see the function being called. Part of the advanced compilation is removing unused code and renaming the methods/variables.
Within your js or html it is never called because the function call is only defined in a string value here :
for (var i = 0; i < individualPagesArray.length; i++) {
document.getElementById("numbers").innerHTML += `<button onclick=showCurrentPage(${i+1})>` + individualPagesArray[i] + `</button>`;
}
you can solve this pretty simply by rewriting this:
window.showCurrentPage = (i) => {
to this:
window['showCurrentPage'] = (i) => {
See : https://developers.google.com/closure/compiler/docs/api-tutorial3#removal
How to Bind Datalsit in clientside using javascript and Jquery.I am using Webservice,if the ajax have success I want to bind the Datalist.I tried some code
function succes(response) {
var value = $.parseXML(response.d);
var xvalue = $(value);
debugger;
var products = xvalue.find("tblProddetails");
var repeatColumns = parseInt("<%=dlViewProd.RepeatColumns == 0 ? 1 : dlViewProd.RepeatColumns %>");
var rowCount = Math.ceil(products.length / repeatColumns);
var i = 0;
while (i < repeatColumns * rowCount) {
var table = $("[id*=dlViewProd] tr").eq(0).clone(true);
for (var j = 0; j < repeatColumns; j++) {
var prod = $(products[i]);
if (prod.length == 0) {
$("table:last", table).remove();
}
else {
$("#img1", table).html($(this).find("ProductImage").text());
$("#lblPrice", table).html($(this).find("ProductPrice").text());
$("#lnkID", table).html($(this).find("ProductName").text());
$("#dlViewProd").append(table).append("<br/>");
table = $("#dlViewProd").eq(0).clone(true);
}
i++;
}
$("[id*=dlViewProd]").append(table);
}
$("[id*=dlViewProd] tr").eq(0).remove();
$("[id*=dlViewProd]").show();
}
this suggest you use it,there is an example in the demo
https://github.com/BorisMoore/jquery-tmpl
I am building a very simple memory game for a small project. The logic is as follows:
click on the input field to choose with how many pairs would you like to play
create divs with classes card1, card2 etc.
clone divs and randomize their place in the array
Here is my script (fork in JSFiddle):
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
// randomize cards in stack
var cards = $(".cards");
for (var i = 0; i < cards.length; i++) {
var target = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
}
});
what I need now is to adjust the 3rd step, meaning to dynamically create the target vars, and the last line of the code
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
So please make me a suggestion - how would you do it? And bare in mind this is a project for beginners. Thank you!
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
var parent = $(".container");
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
});
see jsfidle: http://jsfiddle.net/007y4rju/8/
source: http://jsfiddle.net/C6LPY/2/
Here is the version of the code in jsfiddle - http://jsfiddle.net/007y4rju/6/
Please, check if the behavior is consistent with the original code.
$(document).ready(function () {
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
// randomize cards in stack
var cards = $(".cards");
var startTarget = Math.floor(Math.random() * cards.length - 1) + 1;
var collection = cards.eq(startTarget);
var nextTarget;
var i;
for (i = 0; i < cards.length; i++) {
nextTarget = Math.floor(Math.random() * cards.length - 1) + 1;
collection.before(cards.eq(nextTarget));
}
});
});
You can randomize index in a class name (card%i%) when cloning divs. Then you don't need to shuffle cloned divs; you can append them as is.
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>");
}
var aIndices = [];
for (var i = 1; i <= numCards; i++) {
var ix;
do ix = Math.round(Math.random() * (numCards - 1)) + 1;
while (aIndices.indexOf(ix) >= 0);
aIndices.push(ix);
// clone
$(".card" + ix).clone().appendTo(".container");
}
});
Is there a way to add rows to a gridview using JavaScript? Right now I have the GridView's onclick method set to sortTrGrid(gridviewname) with the sortTrGrid method structured as below. I can get the rows in the tables set in the proper order, however nothing changes on the web page.
function sortTrGrid(sender) {
var table = document.getElementById(sender.id);
var rows = new Array(table.rows);
for (var i = 0; i < table.rows; i++) {
rows[i] = table.rows[i];
}
for (var i = table.rows; i > 0; i--) {
table.deleteRow(document.getElementById(i));
table.rows[i] = rows[i];
}
}//end GridSort
Assuming your page contains all the rows from your data source (no-paging) and you want to order the GridView rows on the client to increase performance (without hitting the server), you can do the following:
(This code allows sorting numbers and text and sorting in ascending and descending mode when clicking the GridView headers)
If you want to check the full working example, I just uploaded to my GitHub site
Screenshot
Unordered
First click - ASC order
Second click - DESC order
Binding the GridView
<asp:LinqDataSource runat="server" ID="lds"
ContextTypeName="WebForms_1.DataAccess.PubsDataContext"
TableName="jobs"
EntityTypeName="WebForms_1.DataAccess.jobs">
</asp:LinqDataSource>
<asp:GridView runat="server" ID="gv" DataSourceID="lds" DataKeyNames="job_id">
</asp:GridView>
jQuery code
<script type="text/javascript">
$(function () {
var $gv = $("table[id$=gv]");
var $headers = $("th", $gv);
var $rows = $("> tbody > tr:not(:has(table, th))", $gv);
$rows.addClass("grid-rows");
$headers.addClass("grid-headers");
$headers.toggle(function (e) {
sortGrid($(this), 0);
}, function (e) {
sortGrid($(this), 1);
});
function sortGrid(row, direction) {
var colIndex = $(row).parent().children().index($(row));
var $rowsArray = $.makeArray($rows);
var $sortedArray = $rowsArray.sort(function (o, n) {
var $currentCell = $("td:nth-child(" + (colIndex + 1) + ")", $(o));
var $nextCell = $("td:nth-child(" + (colIndex + 1) + ")", $(n));
var currentValue = parseFloat($currentCell.text()) ? parseFloat($currentCell.text()) : $currentCell.text();
var nextValue = parseFloat($nextCell.text()) ? parseFloat($nextCell.text()) : $nextCell.text();
if (direction == 0) {
return currentValue < nextValue ? -1 : 1;
}
else {
return currentValue > nextValue ? -1 : 1;
}
});
$("> tbody > tr:not(:has(table, th))", $gv).remove();
$("tbody", $gv).append($sortedArray);
}
});
</script>
I am using the below mentioned code in my VB.net application to print two copies of pdf document.
js.Append("var pp = this.getPrintParams();")
js.Append("var iCopies = 2;")
js.Append("var iPages = this.numPages;")
js.Append("pp.NumCopies = iCopies;")
js.Append("pp.interactive = pp.constants.interactionLevel.silent;")
js.Append("for ( var i = 0; i < iPages; i++ ) { pp.firstPage = i; pp.lastPage = i;")
js.Append("this.print(pp);")
js.Append("}")
It is working great. But how can I make the last page print only 1 copy instead of two copies.
Your help greatly appreciated.
js.Append("for ( var i = 0; i < iPages; i++ ) { pp.firstPage = i; pp.lastPage = i;")
js.Append("if(i == (iPages - 1)) pp.NumCopies = 1; ") ' This line does it
js.Append("this.print(pp);")
js.Append("}")