I am trying to implement pagination for an array where users can navigate using previous and next buttons or by specifying a position. When the index changes, I want the corresponding value to be displayed.
Although I have attempted to achieve this with the code below, I have encountered some issues.
var resultBox = $('#result')
var messages = ["cat", "dog", "fish"];
var idx = $("#pageNumber").val();
var length = messages.length;
var getNextIdx = (idx = -1, length, direction) => {
switch (direction) {
case '1':
{
$("#pageNumber").val((idx + 1) % length + 1)
return (idx + 1) % length;
}
case '-1':
{
$("#pageNumber").val(((idx == 0) && length - 1 || idx - 1) + 1);
return (idx == 0) && length - 1 || idx - 1;
}
default:
{
return idx;
}
}
}
var getNewIndexAndRender = function(direction) {
idx = getNextIdx(idx, length, direction);
console.log(idx)
$("#result").val(messages[idx])
}
$(document).ready(function() {
$("#pageNumber").change(function() {
getNewIndexAndRender()
});
});
getNewIndexAndRender()
$( "#prev" ).trigger( "click" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="result"></textarea>
<input type="text" id="pageNumber" value="0"></input>
<button id="prev" onclick="getNewIndexAndRender('-1')">prev</button>
<button id="next" onclick="getNewIndexAndRender('1')">next</button>