Pagination in vanilla Javascript without any frameworks or libraries - javascript

Stackoverflow! I got a task to create sortable/dynamic table with options to add and remove content and I've managed to do it. My last task however is to make a pagination of 20 rows per page and that's where my 10 days Javascript knowledge is put to a high test. Namely, I can't even put my foot of the ground.
Can anyone help me out in understanding the logic behind the creation of pagination?

here is the code for paginating your table for 20 elements per page:
Edit the function loadTableData() with this:
//Pagination
function loadTableData(movieData, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
var movieDatap = movieData.slice((page_number - 1) * page_size, page_number * page_size);
const tableBody = document.getElementById('tableData');
let txt = '';
for (let i = 0; i < movieDatap.length; i++) {
txt = txt + `<tr><td>${movieDatap[i].name}</td>
<td>${movieDatap[i].genre}</td><td>${movieDatap[i].rating}</td>
<td><button onclick="deleteRow(${i});">Delete</button>
<button onclick="editRow(${i});">Edit</button></td></tr>`;
}
tableBody.innerHTML = txt;
}
function decreaseTableDatas(){
var value = parseInt(document.getElementById('pagenumber').value, 10);
value = isNaN(value) ? 0 : value;
value--;
document.getElementById('pagenumber').value = value;
loadTableData(movieData, 20, value);
}
function incrementTableDatas(){
var value = parseInt(document.getElementById('pagenumber').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('pagenumber').value = value;
loadTableData(movieData, 20, value);
}
window.onload = () => {
loadTableData(movieData, 20, 1);
}
Update the HTML with this:
<div class="pagination">
<div class="pagination-block">
<span class="pageButton outline-none" onclick="decreaseTableDatas()" id="button_prev">Prev</span>
<input type="button" value="1" id="pagenumber" />
<span class="pageButton outline-none" onclick="incrementTableDatas()" id="button_next">Next</span>
</div>
</div>
I hope that is what you are looking for mate

Related

Slidebar which can be adjusted manually

I did a Slidebar (0-99) which is working well.
I want to add 2 buttons to manually change it (first button -1 ; second button +1).
It was working well with my "-1" code for the first button, but the second one isnt working and I dont understand why. (It add 1 but for example if my slidebar is at 50, when i click its not going to 51 but 501).
Here is my code :
<div>
<button id="moins1" onclick="moins1()">MOINS 1</button>
<span class="unselectable rangeValue1" id="rangeValue1">RR</span>
<Input class="range" type="range" name="BarreRR" value="0" min="0" max="99" onChange="rangeSlide1(this.value)" onmousemove="rangeSlide1(this.value)"></Input>
<button id="plus1" onclick="plus1()">PLUS 1</button>
</div>
<script type="text/javascript">
function rangeSlide1(value) {
document.getElementById('rangeValue1').innerHTML = value;
}
function moins1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop -=1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}
function plus1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop +=1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}
</script>
Thanks for help, Zartex.
The issue is that textContent returns string and using + operator will try to concatenate the values. So you can parse it. But I would recommend directly connecting your range with displayed value and only alter the range using the buttons or change them together for example:
function rangeSlide1(value) {
document.getElementById('rangeValue1').innerHTML = value;
}
function moins1() {
let range = document.querySelector('.range')
if (range.value != 0) {
let newValue = range.value - 1
document.getElementById('rangeValue1').innerHTML = newValue
range.value = newValue
}
}
function plus1() {
let range = document.querySelector('.range')
if (range.value < 99) {
let newValue = Number(range.value) + 1
document.getElementById('rangeValue1').innerHTML = newValue
range.value = newValue
}
}
<div>
<button id="moins1" onclick="moins1()">MOINS 1</button>
<span class="unselectable rangeValue1" id="rangeValue1">RR</span>
<Input class="range" type="range" name="BarreRR" value="0" min="0" max="99" onChange="rangeSlide1(this.value)" onmousemove="rangeSlide1(this.value)"></Input>
<button id="plus1" onclick="plus1()">PLUS 1</button>
</div>
Considering your range is limited from 0 to 100 I added condition not to go under 0
it will help you,
Yop value always in "50" + 1 it will return by concat 501
so parseInt your string and add/minus by 1
function moins1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop = parseInt(Yop)-1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}
function plus1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop = parseInt(Yop)+1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}

I was practicing a way to loop numbers to create a times table but the loop only runs one time

I am practicing creating a function that loops whatever number I put into the input into a times table. I used a for loop to achieve this but I ran into an issue. My for loop only runs one time and it only get my input * 10 for some reason. Can someone please help. Thank you.
function myFunction() {
var inputNumber = document.querySelector(".input-field").value;
inputNumber = parseInt(inputNumber);
if (isNaN(inputNumber) || inputNumber == "" || inputNumber == null) {
document.querySelector(".output h1").innerHTML = "Please enter a number!";
} else {
for (i = 1; i <= 10; i++) {
let product = inputNumber * i;
document.querySelector(".output").innerHTML = "<br>" + inputNumber + " * " + i + " = " + product + "<br>";
}
}
}
Looks like you update the HTML on every iteration. However, I think you want to expand the innerHTML to include all elements?
I would look into creating html elements in javascripts and adding them in html like this (draft, untested):
const element = document.createElement("div")
for (let i = 1; i < 10; i++) {
let product = inputNumer * i;
element.appendChild(document.createTextNode(`${inputNumer} ${product}`);
}
Please study this. It is using recommended event listener and a map
const arr = [...Array(11).keys()].slice(1); // numbers from 1 to 10
const h1 = document.querySelector("#output h1"),
result = document.getElementById("result"),
inputField = document.getElementById("inputField");
inputField.addEventListener("input", function() {
const inputNumber = +this.value;
console.log(inputNumber)
h1.classList.toggle("hide", inputNumber); // keep hide if ok number
result.innerHTML = inputNumber ? arr.map(i => `${inputNumber} * ${i} = ${inputNumber*i}`).join(`<br/>`) : "";
});
.hide {
display: none;
}
<input type="number" id="inputField" class=".input-field" />
<hr/>
<div id="output">
<h1 class="error hide">Please enter a number!</h1>
<div id="result">
</div>
</div>

Js returns 0 instead on value

function TipCalc(){
var Amount = Number(document.getElementById("billamt").innerHTML);
var TipPercent = Number(document.getElementById("tipper").innerHTML);
var Answer = 0;
alert(Amount,TipPercent);
if (TipPercent > 0){
Answer = Amount * TipPercent;
document.getElementById("ac").innerHTML ="$ "+ Answer;
}
else{
document.getElementById("ac").innerHTML = "Error!!";
}
}
alert returns 0 instead of values
It's probably simple but i'm new to js
I am not completely sure on what it is you are trying to accomplish with the alert, is it for your reference on the code working or are you trying to calculate the values?
Either way I have modified your alert to show both values
TipCalc()
function TipCalc(){
var Amount = Number(document.getElementById("billant").innerHTML);
var TipPercent = Number(document.getElementById("tipper").innerHTML);
var Answer = 0;
alert(`Amount:${Amount}, TipPercent: ${TipPercent}`);
if (TipPercent > 0){
Answer = Amount * TipPercent;
document.getElementById("ac").innerHTML ="$"+ Answer;
}
else{
document.getElementById("ac").innerHTML = "Error!!";
}
}
function Number(elValue){
return parseInt(elValue);
}
<p id="billant">
42
</p>
<p id="tipper">
4
</p>
<div id="ac">
</div>

I stuck with this code, trying to figure out, how it should work

I'm working on a poject, need it must be auto calculation.
let say that we have uncounted hidden inputs with known same class and attr. diffrent value, attr diffrent price, price2 price 3 in a div to count
What im trying to do is to get attrs (price, priceX2, priceX3)
if the user inserted a number ex. 1 or 40, will return first input(price, priceX2, priceX3), and if its given 61 0r 70 then it will return to the third input(price, priceX2, priceX3) so on
<div id="countDiv">
<input type="number" value="" id="counter" />
<button id="countBtn"> Count </button>
<input type="hidden" value="40" price="1100" priceX2="1200" priceX3="1220" class="classeid">
<input type="hidden" value="60" price="1150" priceX2="1250" priceX3="1300" class="classeid">
<input type="hidden" value="70" price="1220" priceX2="1350" priceX3="1400" class="classeid">
</div>
<script>
$(document).ready(function(){
$("#countBtn").click(function(){
var parentDOM = document.getElementById("countDiv");
var classCounter = parentDOM.getElementsByClassName("classeid");
var counter = $("#counter").val();
for (var i = 0, n = classCounter.length; i < n; ++i) {
var mPrice = parseInt(classCounter[i].value);
var cPrice = parseInt(classCounter[i].getAttribute('price'));
var cPriceX2 = parseInt(classCounter[i].getAttribute('priceX2'));
var cPriceX3 = parseInt(classCounter[i].getAttribute('priceX3'));
}
});
});
</script>
Hope this code help you.
Do do it dynamically it's not better to do using the Hidden field if you have more than 3 input hidden field. The logic will be different in that case.
Considering only 3 hidden input fields then code looks as below:
HTML Code:
provide id to the each hidden input fields as first, second and third as written in the code.
JavaScript Code:
$("#countBtn").click(function(){
var counter = $("#counter").val();
if(counter > 0 && counter <= 40) {
var mprice = $("#first").val();
var cprice = $("#first").attr("price");
var cPriceX2 = $("#first").val("priceX2");
var cPriceX3 = $("#first").attr("priceX3");
}
else if(counter > 39 && counter <= 60) {
var mprice = $("#second").val();
var cprice = $("#second").attr("price");
var cPriceX2 = $("#second").val("priceX2");
var cPriceX3 = $("#second").attr("priceX3");
}
else {
var mprice = $("#third").val();
var cprice = $("#third").attr("price");
var cPriceX2 = $("#third").val("priceX2");
var cPriceX3 = $("#third").attr("priceX3");
}
}

struggling with creating asterisks in Javascript

I've been struggling with this for some time now. What I wanted to create is to output a triangle of asterisks based on user's input. Let say user entered size 5, it would look something like this:
*
**
***
****
*****
My HTML looks like:
<p>
Size: <input type="text" id="size">
<input type="button" value="Draw" onclick="draw()">
</p>
<pre id="output">
</pre>
In my Javascript, I have:
function draw()
{
var size = customJS.get ( "size" ); //I have a custom library where it get the Id from HTML
var theTriangle = makeTriangle( size.value ); //sending in the size
customJS.set ("output", theTriangle); //will set theTriangle to display to "output" in HTML
}
function makeTriangle( theSize )
{
var allLines = ""; // an empty string to hold the entire triangle
for ( var i = 0; i <= size; i++) // this loop size times
{
var oneLine = createLine ( i <= size ); // amount of asterisks for this line
allLines += oneLine;
}
return allLines;
}
function createLine ( length )
{
var aLine = ""; // an empty string to hold the contents of this one line
for ( var j = 0; j <= i; j++ ) //this loop length times
{
aLine += '*';
}
return aLine + "<br>";
}
anyone have any tip on how I go about this? thank you so much!
Newlines in HTML normally display as spaces, but you want them to show as newlines. The pre tag makes newlines actually appear as new lines, so wrap the output in a pre tag:
customJS.set ("output", "<pre>" + theTriangle + "</pre>");
Also, you're calling createLine like this:
var oneLine = createLine ( i <= size );
i <= size yields a boolean (true or false) rather than a number. You probably mean to just pass it i:
var oneLine = createLine ( i );
Additionally, you're setting size like this:
var size = customJS.get = ( "size" );
You probably want to drop the second equals, since as is, it sets the variable size to the string "size".
And finally, you've got a few variables wrong: in makeTriangle, you're looping size times, but size is undefined; you probably meant theSize. In createLine, you're looping i times, but i is undefined; you probably meant length.
With all that, it works.
There were several bugs in your code. For example using theSize instead size as parameter in the function makeTriangle(), using i instead of length in the createLine() function in the for loop condition.
Another one was:
use
return aLine + "<br/>";
instead of
return aLine + "\n";
The working solution for your code can be found in this jsFiddle: http://jsfiddle.net/uwe_guenther/wavDH/
And below is a copy of the fiddle:
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Size:
<input type="text" id="sizeTextField">
<input id='drawButton' type="button" value="Draw">
<div id='output'></div>
</p>
<script src='main.js'></script>
</body>
</html>
main.js
(function (document) {
var drawButton = document.getElementById('drawButton'),
sizeTextField = document.getElementById('sizeTextField'),
output = document.getElementById('output');
function makeTriangle(size) {
var allLines = '';
for (var i = 0; i <= size; i++) {
var oneLine = createLine(i); // amount of asterisks for this line
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 0; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
drawButton.onclick = function () {
output.innerHTML = makeTriangle(sizeTextField.value);
};
})(document);
You can leverage some JavaScript tricks to make the code a bit more terse:
<div style="text-align: center">
<label>Size:
<input type="text" id="size" value="5">
</label> <pre id='output'></pre>
</div>
<script>
var size = document.getElementById('size'),
output = document.getElementById('output');
function update() {
var width = +size.value, // Coerce to integer.
upsideDown = width < 0, // Check if negative.
width = Math.abs(width), // Ensure positive.
treeArray = Array(width).join('0').split('0') // Create an array of 0s "width" long.
.map(function(zero, level) { // Visit each one, giving us the chance to change it.
return Array(2 + level).join('*'); // Create a string of *s.
});
upsideDown && treeArray.reverse(); // If width was negative, stand the tree on its head.
output.innerHTML = treeArray.join('\n'); // Join it all together, and output it!
}
size.onkeyup = update;
update();
size.focus();
</script>
http://jsfiddle.net/mhtKY/4/

Categories

Resources