I am utilizing Vue.js to create a duplicate input field and dynamically increasing the index

When a user clicks on the "add another" button, I want to create a duplicate text input field and increase the index of the new field. I found this question that is similar, but the solution provided did not successfully increment the index.

The current implementation duplicates the field and increments the index, but it affects all indexes rather than just the newest one (thanks to Roy J for pointing this out).

Below is the template being used:

<div id="app">
  <template v-for="slot in timeslots">
    <div><input type="text" name="performances[@{{ count }}][timestamp]" v-model="slot.timestamp" placeholder="index @{{ count }}"></div>
  </template>
  <span class="add green btn" @click="addAnother"><i class="fa fa-plus-circle"></i> Add another</span>
  <pre>@{{ timeslots | json }}</pre>
</div>

Here is the corresponding Vue JS code:

new Vue({
  el: '#app',

  data: {
      timeslots: [
          {
            timestamp: '',
            count: 0
          }
      ],
      count: 0
  },

  methods: {
    addAnother: function(){
      this.timeslots.push({
        timestamp: '',
        count: this.count++
      });
    }
  }
});

Answer №1

In order to prevent duplicates in the first elements, I found that simply adding this before count++ worked for me.

I have updated the placeholder text to reference slot.count instead of the parent count.

new Vue({
  el: '#app',

  data: {
    timeslots: [{
      timestamp: '',
      count: 0
    }],
    count: 0
  },

  methods: {
    addAnother: function() {
      this.timeslots.push({
        timestamp: '',
        count: ++this.count
      });
    }
  }
});
.green.btn {
  background-color: green;
  color: white;
  padding: 5px;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="app">
  <template v-for="slot in timeslots">
    <div>
      <input type="text" name="performances[@{{ slot.count }}][timestamp]" v-model="slot.timestamp" placeholder="index {{ slot.count }}">
    </div>
  </template>
  <span class="add green btn" @click="addAnother"><i class="fa fa-plus-circle"></i> Add another</span>
  <pre>@{{ timeslots | json }}</pre>
</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

Having trouble with my jQuery .hover() code not running as expected

Whenever I hover over my divs, I want them to change color. However, the code doesn't seem to be working as expected when I try to do so. I suspect that the issue might be related to the z-index property used in the class that I am trying to hover ove ...

The process of dynamically populating data into a select element through an Ajax request using JavaScript may seem complicated at

I am working on an html page that includes two select options. The values for these select options are retrieved from a Servlet via an ajax call in the onclick() function. However, I am encountering an issue where the data is not populating into the sele ...

There seems to be a glitch preventing Highchart from functioning within a jQuery function

Hello there! I'm currently utilizing the highchart API to generate graphs in a loop. for(i=1;i<10;i++) { xseries = "{'INCOPAV','B&M','SGS-ETSA'}"; yseries = "[{name: &apos ...

Creating a Fresh Row - Steps to Activate Datepickr on a Copied Row

Whenever a button is pressed, a row in a table duplicates itself. Here is a snippet of the code: <tr> <td valign="top"><input type="text" name="session[]" size="15"></td> <td valign="top"><textarea name="descr[]" cols="40" ...

The function is not triggered when the select tag is changed

I'm currently working on implementing a drop-down menu using the <select> element in HTML. Here is the code snippet I have so far: <select id="Parameter1" onchange="function1()"> <option value = "0105" name = "Frequency">Frequency ...

In Vue.js2, you can easily compare two arrays of objects that have the same values and then make changes or add properties from one array to the other

I am working with an array of objects fetched from an API (), which is linked to a variable that serves as the v-model for an input. Whenever the variable changes, so does the array through a function that triggers the API call on @keyup. The structure of ...

When the page loads, the HTML side menu will automatically scroll to the active item in a vertical

My website features a vertical side menu with approximately 20 items. The issue I am facing is that when a user clicks on an item, the destination loads but the side menu must be manually scrolled to find the active item if it's located at the bottom ...

What is an effective method for coordinating JQuery animations simultaneously?

My current understanding of $("#someElement").animate() is that it will run asynchronously in relation to other JavaScript statements. For example: $("#anotherElement").css("display", "none"); $("#someElement").animate(); //The CSS display may change a ...

Revamp your array elements with MongoDB - Substring replacement

Having some difficulty replacing a substring within various documents. Below is an example of one such document: { "images" : [ { "url" : "https://example/1234" }, { "url" : "https://example/afaef" }, { "url" : ...

What steps do I need to take to extract the date and month from a single datepicker using the code below?

<div class="col-md-3 pull-left" style="padding:9px"> <input type="text" id="datepicker" class="form-control"> </div> The HTML and C ...

Sending data as a string in an AJAX request

I have been struggling with this coffeescript function that controls dynamic select boxes. I am trying to pass the content of "modelsSelect" to another script, but for some reason, it's not working as intended. customScript.coffee dynamicSelection = ...

What is the best way to display a SolidJS component on the screen?

I am currently working on a unique menu design for my application. The concept involves rendering a functional component within an element created in the body using createRoot and render methods. https://i.stack.imgur.com/g6Ofv.png export function create ...

The type does not have a property named 'defaultProps'

I have a Typescript React class component structured like this: import React, { Component } from 'react'; interface Props { bar?: boolean; } const defaultProps: Partial<Props> = { bar: false, }; class Foo extends Component<Props& ...

Implement a Basic Custom Shader on a Cube in Three.js

Struggling with applying a basic custom shader to a cube in Three.js. Whenever I attempt to use the shader, the cube mysteriously vanishes. No issues when using a standard Toon or Lambert Material - cube rotates and behaves as expected. Oddly, Orbit Contr ...

All strings located between the specified phrases

I am attempting to extract strings that are located between two specific strings, but the output I am getting from using str.match is not what I anticipated: var text = "first second1 third\nfirst second2 third\nfirst second3 third"; var middles ...

Issue: The n-api module is not being recognized due to an error stating "Cannot read property 'indexOf' of undefined"

After developing a C++ module using n-api and compiling it with cmake-js, I encountered an issue when trying to integrate it into my electron-vue application. Surprisingly, the module worked fine in other projects without electron-vue. However, every attem ...

What is the best way to transmit extra data when tunneling a TLS connection?

I have developed a basic HTTP proxy that utilizes the HTTP CONNECT method for HTTP tunneling. const http = require('http'); const https = require('https'); const pem = require('pem'); const net = require('net'); con ...

Instructions on generating a fresh Ethereum or Solidity contract for every test using JavaScript and Truffle

overview After developing an Ethereum smart contract using the Solidity language, I utilized Ganache to deploy my contract for testing purposes. However, in order to conduct tests effectively, I need to create a new instance of my contract using JavaScrip ...

In my chat application, I encountered the error message "Received an expression instead of an assignment or function call - no-unused-expressions"

While working on my React Chat app and trying to access my Firebase, I encountered the error message: "Expected an assignment or function call and instead saw an expression no-unused-expressions" The error seems to be related to the assignment of this.rem ...

Mobile page sliding mechanism

My website contains a div that is mostly off the page, but on hover it translates onto the main page. You can check out my website. However, this method doesn't work well on mobile devices. Hovering is not effective and I often have to click multipl ...