Divide the text array into pages within an HTML textarea using a loop

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>

Answer №1

Ensure that in your change function, the variable idx is reassigned to be equal to the current input value minus 1.

$("#pageNumber").change(function() {
  idx = $(this).val() - 1;
  getNewIndexAndRender();
});

Check out this interactive demonstration:

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);
  $("#result").val(messages[idx]);
}

$(document).ready(function() {
  $("#pageNumber").change(function() {
    idx = $(this).val() - 1;
    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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A database table named after a pair of digits

My database tables are named "30" and "kev." When I query the table named "30," I receive the following error message: Warning: Invalid argument supplied for foreach() in # on line 94 However, when I query the kev table, I do get the desired results. B ...

The background image will expand to fill any available space

I'm currently working on rendering divs with a background image CSS property. The images have fixed sizes, and I want to display them in a grid layout. However, the divs with background images stretch when there is extra space available, which is not ...

Multiple 'keydown' events are accumulating with Ajax activated

When the search field is focused, I am loading JSON into the browser and then iterating over the JSON objects to find real-time results 'on keydown'. The issue I'm encountering is detailed in the console after the initial block of code Aja ...

What steps are involved in extracting post data from the javascript DOM using php?

Having an issue where my JavaScript sends data to PHP, but the parsing in PHP keeps failing. The data is received by PHP and displayed in a text area, however, it needs proper formatting before being parsed. Can anyone advise on how to correctly format the ...

scrollable list using bootstrap

<div class="panel panel-primary" id="result_panel"> <div class="panel-heading"><h3 class="panel-title">List of Results</h3> </div> <div class="panel-body"> <ul class="list-group"> &l ...

Using jQuery to incorporate a variable into JSON schema markup

For my current project, I am attempting to extract the meta description and incorporate it into JSON schema markup. However, I am facing difficulty in passing the variable properly into the JSON structure. My initial approach was as follows: <script&g ...

Is it possible to deactivate an anchor tag based on the result of a conditional statement that returns a string?

I've created an anchor tag (not a button) with text that redirects me to another page <StyledTableCell align="center"> <Link href={`/races/results/${race.id}`}>{race.race_name}</Link> </StyledTableCell> There is a ...

Ways to extract the text from a modifiable div using angularjs

I am currently facing a challenge in extracting content from an editable div. I am having trouble incorporating the Angular template for this task. The part that is posing a difficulty for me is figuring out how to link model data from the HTML template t ...

Incompatibility Issue with Ajax Request on iPad 1 (iOS 5.1.1)

Having an issue with reloading content on my iPad web app. The get request works fine in the browser, but I'm experiencing trouble in Safari on the iPad 1 (iOS 5.1.1). Any suggestions on how to fix this? <script type="text/javascript"> ...

What is the best way to create a variable in a React component that requires asynchronously loaded data in order to be functional?

While I have a good understanding of passing data from one component to another using this.props, I am encountering difficulty in asynchronously fetching and storing values, such as from a database, that need to be accessed throughout the component. The ch ...

Having trouble applying the alternate style sheet to handheld devices

For a single page, I have implemented two different style sheets. <link rel="stylesheet" href="css/lsharecomplete_mob.css" media="handheld" type="text/css" /> <link rel="stylesheet" href="css/lsharecomplete_dt.css" type="text/css" media="Screen" ...

Is there a way to cycle through each element within a loop and output a corresponding item from another array?

My data structure consists of an array of objects like this: arrOfObjs = [{type: "flower", egg: "something"}, {type: "flower", egg: "something2"}, {type: "notFlower", egg: "something3"}, {type: &q ...

What is the best way to extract JSON data from a remote URL?

Having recently started with JavaScript, I am looking to parse JSON from an external URL using pure JavaScript. Currently, I have the following code: var getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, tr ...

Implement API filtering using JavaScript

Looking to streamline the data filtering process for a car website where API queries involve parameters like brand, color, price, and fuel. https://i.sstatic.net/OYUxs.png The mock API being used is located at https://api.example.com/api/v1/it/vehicles ...

What is the best way to shift a text element within the footer section?

I have arranged two columns within the container, but I am looking to position the .company and .copyright text at the bottom left of the footer column. The Follow Us heading should be on the right side with the .justify-text below it, followed by social m ...

What is the best way to vertically center a div that has a fixed position and a specific width in pixels

Is there a way to center a fixed position div with a specified width of 300px, rather than in percentage? <div class="mainCont"> <div class="childCont"> </div> The childCont div has a fixed position and width of 300px. How can I ensur ...

JavaScript node failing to update variable value with promise value

I am facing an issue with the following code snippet- let { user } = req.body; let name = null; if (!user) { getStudent(id).then((x) => { user = x.user; name = x.name; }); } console.log(user, name); // prints undefined and null Despite us ...

The animation-play-state is set to 'running', however, it refuses to start playing

I'm in the process of creating a landing page that includes CSS animations, such as fade-ins. Initially setting animation-play-state: "paused" in the CSS file, I later use jQuery to trigger the animation while scrolling through the page. While this s ...

What is the process for triggering an unordered list when I click on a table data cell within the Hospitals category?

Hi there! I need help with writing a JavaScript function for Hospitals in the code below. When I click on Hospitals, I want to display the values in the unordered list. Expected output: Hospitals--->onclick Bangalore| salem |Goa| Mangalore| Visakhapat ...

execute the command only if all ava tests succeed

I'm working on creating an npm script that will execute Ava, and if it is successful, will then run another deploy command. Is there a way to obtain the result of an Ava test in JavaScript, or to save it to a file or pass it to a subsequent command? ...