How can dynamic values be displayed in VueJS?

I'm looking to display dynamic titles based on the number of times a value is added. For example, if a user selects cats and clicks Add, I want the title to show as cats 1. If the user adds it again, then it should be displayed as cats 2, and so on for dogs. I'm currently struggling to solve this issue.

You can find the solution in action on this codepen.

This is the Vue.js code that works:

new Vue({
  el: "#app",
  data() {
    return {
      selected: [],
      animalList: [],
      moreAnimals: [{
          title: "cat",
          value: "cat"
        },
        {
          title: "Dog",
          value: "dog"
        }
      ]
    };
  },
  methods: {
    createTitle() {
      this.animalList = this.animalList.concat(this.selected);
      console.log(this.animalList);
      this.selected = [];
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06707363726f607f46372833283732">[email protected]</a>/dist/vuetify.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22545747564b445b62130c170c1316">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout row wrap>
        <v-flex xs2 v-for="(animal,index) in animalList" :key="`${animal.value} - ${index}`">
          {{animal.value}}
        </v-flex>
      </v-layout>
      <v-flex v-for="(more,index) in moreAnimals" :key="`${more.value} - ${index}`">
        <v-checkbox :value="more" v-model="selected" :label="more.title">
        </v-checkbox>
      </v-flex>
      <v-btn @click="createTitle">Add</v-btn>
    </v-container>
  </v-app>
</div>

Your assistance is greatly appreciated. Thank you!

Answer №1

To accomplish this task, you must locate the most recently added animal of the same category, extract the numerical value at the end of its identifier, and increment it before appending it to the new animal's identifier:

new Vue({
  el: "#app",
  data() {
    return {
      selected: [],
      animalList: [],
      moreAnimals: [
        {
          title: "cat",
          value: "cat"
        },
        {
          title: "Dog",
          value: "dog"
        },
        {
          title: "camel",
          value: "camel"
        },
      ]
    };
  },
  methods: {
    createTitle() {
      for(let i = 0; i < this.selected.length; i++){
        let currentSelected = Object.assign({}, this.selected[i]);
        if(currentSelected.title != "camel")
             currentSelected.value = this.getAnimalName(currentSelected.title);
        this.animalList.push(currentSelected);
      }
      this.selected = [];
    },
    getAnimalName(title){
      let lastAnimal = null;
      for(let i = 0; i < this.animalList.length; i++)
         if(this.animalList[i].title == title)
           lastAnimal = this.animalList[i];
      let index = (lastAnimal) ? Number(lastAnimal.value.split(" ")[1])+1 : 1;
      return title+' '+index;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d6e6b6b6e706f70446d72797c7979507d">[email protected]</a>/dist/vuetify.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="490a05050a140b0423647b607b6471">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />
...
... (continued with remaining code)
...</answer1>
<exanswer1><div class="answer accepted" i="61704654" l="4.0" c="1589052681" m="1589101142" v="1" a="TWFqZWQgQmFkYXdp" ai="7486313">
<p>You can do that by getting the latest added animal of this type, parsing the number at the end of its value, and incrementing it to append it to the value of the animal to be added:</p>

<p><div>
<div>
<pre class="lang-js"><code>new Vue({
  el: "#app",
  data() {
    return {
      selected: [],
      animalList: [],
      moreAnimals: [
        {
          title: "cat",
          value: "cat"
        },
        {
          title: "Dog",
          value: "dog"
        },
        {
          title: "camel",
          value: "camel"
        },
      ]
    };
  },
  methods: {
    createTitle() {
      for(let i = 0; i < this.selected.length; i++){
        let currentSelected = Object.assign({}, this.selected[i]);
        if(currentSelected.title != "camel")
             currentSelected.value = this.getAnimalName(currentSelected.title);
        this.animalList.push(currentSelected);
      }
      this.selected = [];
    },
    getAnimalName(title){
      let lastAnimal = null;
      for(let i = 0; i < this.animalList.length; i++)
         if(this.animalList[i].title == title)
           lastAnimal = this.animalList[i];
      let index = (lastAnimal) ? Number(lastAnimal.value.split(" ")[1])+1 : 1;
      return title+' '+index;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27563030213c333826657a616a65505622">[email protected]</a>/dist/vuetify.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a090c0c0d100f00493d202b202f2a2a472a">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />
<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout row wrap>
        <v-flex xs2 v-for="(animal,index) in animalList" :key="`${animal.value} - ${index}`">
          {{animal.value}}
        </v-flex>
      </v-layout>
      <v-flex v-for="(more,index) in moreAnimals" :key="`${more.value} - ${index}`">
        <v-checkbox :value="more" v-model="selected" :label="more.title">
        </v-checkbox>
      </v-flex>
      <v-btn @click="createTitle">Add</v-btn>
    </v-container>
  </v-app>
</div>

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

How can I achieve the functionality of an image changing when clicked and going back to its original state upon release with the help of HTML

I am facing an issue with styling an element to look like a button and function as a clickable link. My goal is to create a visual effect of a pressed button when it is clicked, while also loading the target page. For reference, here is a (non-working) J ...

Try out a Vue.js Plugin - A Comprehensive Guide

Currently, I am delving into the world of Vue.js. In my journey, I have crafted a plugin that takes the form of: source/myPlugin.js const MyPlugin = { install: function(Vue, options) { console.log('installing my plugin'); Vue.myMetho ...

Easiest homemade variations and pairings

Imagine having a basic array like ["apple", "banana", "lemon", "mango"];. For example, if we were to find the straightforward hand-rolled combinations of this array, selecting 3 items, but allowing for repetition: let array = ["apple", "banana", "lemon", ...

When you hit the enter key in a text input field in JavaScript, it triggers a specific function

http://codepen.io/abdulahhamzic/pen/YqMQwB Is there a way to make it so that when I hit the enter key on a text input, it triggers a specific function? I attempted to achieve this using the following code: <input type="text" onkeypress=" ...

HTML Button without Connection to Javascript

When attempting an HTML integration with GAS, the code provided seems to be generating a blank form upon clicking "Add" instead of functioning as expected: //GLOBALS let ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var lastRow = ss.getLa ...

Separate line rendering of checkboxes in CSS and Vue

I am struggling with styling Vue checkboxes to display side by side until they wrap to a new line. I have tried modifying the code structure, but the existing CSS classes are causing issues. I have created a simplified example on CodeSandbox. Here is a sn ...

Recursive methodology for building DOM tree structure

var div = { element:'div', parent:'body', style: { width:'100px', height:'100px', border:'1px solid black' } child: { element:'input', type:'text', ...

Troubleshooting the display of API-generated lists in Angular 8

I am encountering an issue in Angular 8 when trying to display my list on a page. Below is the code from my proposal-component.ts file: import { Component, OnInit, Input } from "@angular/core"; import { ActivatedRoute, Params } from "@angular/router"; imp ...

Having trouble with a basic select tag and options not functioning properly in Chrome browser

I encountered an issue where I am unable to expand a simple select tag in Chrome. <select id="filterCategory" class=""> <option>1</option> <option>2</option> <option>3</option> <option>4</option ...

How to dynamically insert a hyperlink inside a <td> element within a table using JavaScript

What is the best way to create a hyperlink in a <td> within a dynamic table? I want the first <td> to be a link that combines a URL with the cell value. This is how the dynamic table is created: for (var i = 0; i < riskData.length; i++) { ...

Enhancing Online Presence with Video Gallery Website Development

I'm in the process of creating a website and need help finalizing my video page. I envision a layout similar to this example: https://i.stack.imgur.com/hctui.gif The main feature should be a large video placeholder at the top, followed by several thu ...

Can the v-for props be successfully transferred to a component that is slotted into the HTML? Unfortunately, the slot props are not functioning as expected

Is there a way to pass the "instance" property of the v-for loop to the slot and use it in a component added to that slot in the HTML? List Component <template> <two-col-row-display :field="field" :fieldcss="fieldcss" :valuecss="val ...

What are the steps to fetch JSON data from a different domain server using AJAX?

I'm facing an issue with the API I'm using for my ajax call. It returns json and does not support jsonp, which unfortunately cannot be changed. Every time I try to use the code snippet below, I encounter a 'missing ; before statement' e ...

Vanilla JavaScript - Conceal all remaining div elements

I have a situation where multiple divs are only visible after clicking a link. How can I ensure that when one div is clicked, all others are closed so that only the clicked one remains visible? Currently, I am using the following JavaScript: functio ...

Forwarding to another page following an AJAX post request to a Django view

I've been struggling to get this basic piece of code to work properly, despite trying numerous resources. I can't seem to pinpoint where I'm going wrong. Essentially, I have a javascript function submitData() that is supposed to make an ajax ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

Uninstall all packages that are no longer listed in the package.json file using Npm

Seeking guidance on how to uninstall packages from the node_modules directory that are no longer listed in package.json. These packages were removed by another developer and the package.json file has been updated on git. Any tips on how to accomplish this ...

having trouble retrieving 200 status code from Angular server response

Objective: I need to make certain changes to the record locally if the server responds with a 200 code. Problem: I am unable to retrieve the response code or access the 'message' attribute. This is the server response I receive from the HTTP ca ...

Learn how to effectively transfer parameters between two React components

I am currently working on a component that looks like this: pays11 = iconAllemagne; pays12 = iconHungrier; score11_12='2 - 2'; bonus11_12 = 'x0'; render() { return ( <Page> ...

Creating a React component that initializes its state with an empty array

Currently, my component is designed to fetch data from an API and store a random selection of objects (currently set at 10) in an array called correctAnswerArray. To avoid selecting the same object more than once, I use the splice() method. After pushing t ...