Vuejs: Limiting the number of items in an li tag to 5

 selectPreviousSearch(index) {
        this.search = this.searchHistory[index];
        this.showSearchHistory = false;
      },
   <input class="form-control bg-light-blue" id="SearchText"  type="text" v-model="search"
        @keydown.enter = 'enter'
        @click="onClick"
        
        @keyup.enter="processSearch"
        @input = 'change'
        @keyup="inputChanged"
        @keydown.down="onArrow"
        @keydown.up="onArrow"
    />
     <ul class="list-group" v-if="showSearchHistory">
            <li class="list-group-item" v-for="(item, index) in searchHistory" :key="index"
              @click="selectPreviousSearch(index)">{{ item }}</li>
          </ul>

I need to limit the number of items stored in the list to five for the li tag.

Essentially, I am designing an input field where any character typed by the user will be saved in a list.

For each li element, I aim to enforce a restriction that only five items can be stored in selectPreviousSearch.

Answer №1

To display the 5 most recent entries in descending order, you can use the following code:

v-for="(item, index) in searchHistory.slice(-5).reverse()"

Edited by @taneeru dhanunjay

@keydown.space="preventLeadingSpace"
 preventLeadingSpace(e) {
      // only prevent the keypress if the value is blank
      if (!e.target.value) e.preventDefault();
      // otherwise, if the leading character is a space, remove all leading white-space
      else if (e.target.value[0]==' ') e.target.value = e.target.value.replace(/^\s*/, "");
    },

Answer №2

Approach 1:

v-for="(item, index) in searchHistory.slice(Math.max(0, searchHistory.length-5))

returnLatestSearch(index) {
    index += Math.max(0, searchHistory.length-5);
    index = index<0?0:index;
    this.searchResults = this.searchHistory[index];
    this.showSearchHistory = false;
 },

Approach 2: modify the method to only retain the last 5 inputs saved in searchHistory.

onInputUpdate(newInput){
    if(searchHistory.length >=5){
        searchHistory.shift();
    }
    searchHistory.push(newInput);
}

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

What is the best method for inserting a 'Placeholder' in an Angular datePicker?

Looking for assistance with placing placeholder text inside an Angular datePicker, specifically wanting to display 'From' and 'To' labels within the datePicker. datePicker I am a novice when it comes to Angular development - can someon ...

Tips on updating the $authProvider.loginUrl for Satellizer from an Angular controller

Consider this hypothetical situation: A user attempts to access a /settings page without being logged in. The Settings controller detects based on $auth.isAuthenticated() != true that the user is not logged in, and directs them to the /login page. The us ...

iterating over a list of files using JavaScript

I am currently working on setting up individual ajax requests for each file being uploaded. I have a functioning ajax call that creates a record, returns some html, and provides the tempID of the record which is then used in another ajax call that triggers ...

Creating objects in Angular 2 through HTTP GET calls

Recently, I've delved into learning Angular 2. My current challenge involves making http get requests to retrieve data and then constructing objects from that data for later display using templates. If you believe my approach is incorrect, please feel ...

Proper syntax for SVG props in JSX

I have developed a small React component that primarily consists of an SVG being returned. My goal is to pass a fill color to the React component and have the SVG use this color. When calling the SVG component, I do so like this: <Icon fillColour="#f ...

Creative ways to conceal JavaScript within your Wordpress website

After placing my javascripts in the header.php file, I realized that the code could easily be snatched by viewing the source on any post or homepage... Can you recommend a straightforward method to conceal my javascripts in WordPress and prevent them from ...

Using inline SVG within a Vue.js component

Recently, I embarked on a Vuejs project using @vue/cli version 3.0.0-beta.16. In my Home.vue single file component, I encountered an issue while trying to import and add inline SVG to the template. The crux of the problem lies in the fact that vue cli alr ...

Nested loops with synchronous calls running in parallel

Is there a way to make synchronous calls in two nested 'for' loops in Node.JS? I have an Asynchronous call, but I am unsure how to modify it to work synchronously and go to the next iteration when create_db is done! var new_items = []; f ...

How to efficiently import Xlsx and csv files using AngularJS

I am looking for a way to extract data in json format from each line of xlsx and csv files using AngularJS. Currently, I am utilizing the angular-file-upload library to access the file as shown below: $scope.LatLongUploader = new FileUploader({ //url ...

Tips for selecting the initial and final elements of a specific class

Here is a simple example of table markup: <div class="table"> <div class="table__headers"></div> <div class="table__row"></div> <div class="table__row"></div> </div& ...

Is it possible to reuse a variable within a single HTML tag when using Angular 2?

I encountered a strange issue with Angular 2 that may be a bug. I noticed that I couldn't print the same variable in a template twice within the same HTML tag. When I tried to use the following code, it resulted in error messages. <div class=" ...

When attempting to call Firebase Functions, ensure that Access-Control-Allow-Origin is set up correctly

Although it may seem straightforward, I am confused about how Firebase's functions are supposed to work. Is the main purpose of Firebase functions to enable me to execute functions on the server-side by making calls from client-side code? Whenever I t ...

Error encountered: Jquery - function is not defined

Currently, I am developing a widget that is integrated into a client's website and it loads a jQuery file. However, we need to check if jQuery is already loaded on the client's page to prevent any conflicts, in which case we would not load our ow ...

Is there a method available for troubleshooting unsuccessful AJAX requests? Why might my request be failing?

Whenever I click on a button with the class "member-update-button," an alert pops up saying "got an error, bro." The error callback function is being triggered. Any thoughts on why this might be happening? No errors are showing up in the console. How can I ...

Can one utilize HTML's .querySelector() method to target elements by xlink attribute within an SVG document?

Here is the scenario: <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <a xlink:href="url"></a> </svg> </body> Now, can you utilize the HTML DOM's .querySe ...

Tips for avoiding errors when determining the length of a child node in Firebase within a vue.js application by utilizing the "Object.keys" function

Let's envision a Vue.js application where the data structure stored in firebase looks something like this: item: { name: itemName, childOne: { subChildA: true, subChildB: true }, childTwo: { subChildA: true, subChildB: true ...

Custom template for label in Vue 2 select2 framework

Is it possible to customize the label slot in a similar way to how we can change the template for the option slot in Vue Select? <v-select inputId="originsId" :options="origins" label="city" placeholder="Search..."> <template slot="option" ...

Is Angular 4 failing to set headers properly or is Express.js searching in the wrong place?

When interacting with an Express.js API, I encountered a issue regarding the handling of auth tokens. The problem arose when sending the token in the request headers using Angular 4 compared to Postman. In Postman, setting the header named 'Authorizat ...

Issue with Bootstrap v3.3.6 Dropdown Functionality

previewCan someone help me figure out why my Bootstrap dropdown menu is not working correctly? I recently downloaded Bootstrap to create a custom design, and while the carousel is functioning properly, when I click on the dropdown button, the dropdown-menu ...

Exploring the power of promises in the JavaScript event loop

Just when I thought I had a solid understanding of how the event loop operates in JavaScript, I encountered a perplexing issue. If this is not new to you, I would greatly appreciate an explanation. Here's an example of the code that has left me scratc ...