Vue: Duplicating a div element with unique input fields upon clicking

I have successfully set up a page where I can dynamically add a div/row of inputs by clicking the link. This feature works smoothly and adds the same div below the current one with all the proper inputs.

Additionally, one of the inputs is designed as an autosuggest/autocomplete search box, which also functions perfectly. When I type in the input, it searches and returns relevant results. Clicking on a result replaces the text in that input as expected.

While these two main functionalities are working flawlessly, I am facing an issue. When I add one or more divs, the text entered in each input reflects the same content. In other words, if I type 'Test' into the third row's input, it will appear in every div/row's input.

Is there a way to resolve this so that each added div's input displays its own text while still being added to the same v-model array?

Answer №1

new Vue({
  components: {},
  el: "#commonNameDiv",
  data() {
    return {
      searchString: [''],
      results: [],
      savedAttributes: [],
      cards: ['']
    }
  },
  methods: {
    autoComplete(index) {
      this.results = [];
      console.log(this.searchString[index]);
      if (this.searchString[index].length > 2) {
        this.results = [{
            attribute_value: "apple"
          },
          {
            attribute_value: "banane"
          }
        ]
      }
    },
    saveAttribute(result) {
      this.savedAttributes = [];
      console.log('cool');
      this.savedAttributes.push(result.attribute_value);
      console.log('here is the attribute');
      console.log(this.savedAttributes);
      this.searchString = result.attribute_value;
      this.results = [];
    },
    addCard: function() {
      this.cards.push({
        index: ''
      })
    }


  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="commonNameDiv">
  <div v-for="(card,index) in cards" class="uk-grid">
    <div class="uk-width-2-10">
      <input size="4" type="text" name="mapNumber">
    </div>
    <div class="uk-width-6-10">
      <input style="width:100%" type="text" placeholder="what are you looking for?" v-model="searchString[index]" v-on:keyup="autoComplete(index)" class="form-control">
      <div class="panel-footer componentList" v-if="results.length">
        <ul class="list-group">
          <li class="list-group-item" v-for="result in results">
            <a v-on:click="saveAttribute(result)">@{{ result.attribute_value }}</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="uk-width-2-10" style="border: 1px solid black; height:50px; width: 50px; margin: 0 auto;">

    </div>
  </div>

  <div style="height: 35px;">

  </div>

  <div>
    <a v-on:click="addCard">Add another zone</a>
  </div>
</div>

Answer №2

If you are experiencing issues, it might be because your cards are connected to the single data property searchString through v-model. To resolve this issue, each card should be linked to its own individual property.

To address this, consider adding a new property to every object within your cards array. This can be accomplished within the addCard method. For example:

addCard: function () {
  this.cards.push({searchString: ''}) // assign a unique searchString value to each card
}

In your template, it would look something like this:

<div v-for="(card,index) in cards" class="uk-grid">
...
  <div class="uk-width-6-10">
    <input ... v-model="card.searchString"> // connect input value to each card's specific searchString property
...
<div>
    <a v-on:click="addCard">Add another zone</a>
</div>
...

Following these steps should help resolve the problem you are facing.

Answer №3

Let's define searchString as an array and utilize the v-model with

v-model="searchString[index]"
. Below is the functional code snippet.

new Vue({
  components: {},
  el: "#commonNameDiv",
  data() {
    return {
      searchString: [' '],
      results: [],
      savedAttributes: [],
      cards: []
    }
  },
  methods: {
    autoComplete() {
      this.results = [];
      console.log(this.searchString);
      if (this.searchString.length > 2) {
        axios.get('/product/parts/components/search', {
          params: {
            searchString: this.searchString
          }
        }).then(response => {
          this.results = response.data;
          console.log(this.results);
          console.log(this.searchString);
        });
      }
    },
    saveAttribute(result) {
      this.savedAttributes = [];
      console.log('cool');
      this.savedAttributes.push(result.attribute_value);
      console.log('here is the attribute');
      console.log(this.savedAttributes);
      this.searchString = result.attribute_value;
      this.results = [];
    },
    addCard: function() {
      this.cards.push({
        index: ''
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='commonNameDiv'>
  <div v-for="(card,index) in cards" class="uk-grid">
    <div class="uk-width-2-10">
      <input size="4" type="text" name="mapNumber">
    </div>
    <div class="uk-width-6-10">
      <input style="width:100%" type="text" placeholder="what are you looking for?" v-model="searchString[index]" v-on:keyup="autoComplete" class="form-control">
      <div class="panel-footer componentList" v-if="results.length">
        <ul class="list-group">
          <li class="list-group-item" v-for="result in results">
            <a v-on:click="saveAttribute(result)">@{{ result.attribute_value }}</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="uk-width-2-10" style="border: 1px solid black; height:50px; width: 50px; margin: 0 auto;">

    </div>
  </div>

  <div>
    <a v-on:click="addCard">Add another zone</a>
  </div>
</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

Struggling to make npm and sqlite3 function properly on MacOS Catalina

Struggling with npm package installation in a project directory on my Mac has proven to be quite the challenge. Each attempt at a simple npm install results in perplexing errors that I can't seem to grasp. The hurdle seems to center around specific p ...

Minor Chrome compatibility problems with CSS alignment

As someone who is new to stackoverflow, I've always found it to be a valuable resource for answers. I've had success building HTML 5 banner ads using GSAP (Greensock Animation Platform) in the past, but now I'm facing a CSS alignment issue t ...

Is the presence of an excessive number of arguments in the object that includes functions an instance

In my program, I have implemented a feature where the user can provide an array to determine which functions are executed in a loop. However, managing the list of variables that need to be passed into each function has become challenging as the list keeps ...

What are the steps for initializing a session in Vue.js with Django upon a successful login?

Upon successful login, I want to redirect to a page indicating success and also include a session. How can this be achieved? I am using HTML with Vue.js for the front end and Django for the back end. Below is my Vue.js script for the login: <script> ...

A Simple Guide to Setting a Background Image in React Native with the Nativebase.io Library

What is the process for including a background image in React Native with the help of the Nativebase.io Library? I have a specific screen where I need to incorporate a background image, with all other elements positioned at the center of the image. ...

What is the best way to perform a callback after a redirect in expressjs?

After using res.redirect('/pageOne') to redirect to a different page, I want to call a function. However, when I tried calling the function immediately after the redirect like this: res.redirect('/pageOne'); callBack(); I noticed th ...

Having an issue with the pop state function not functioning correctly

I am facing an issue with my images where clicking on a specific image changes the URL to that ID. However, I can only go back once and then the same URL is repeated every time I press the back button. Additionally, the forward button does not work at all. ...

Data retrieval seems to be encountering issues in Firefox and IE9, whereas Chrome and Safari are functioning without any problems

I am using the following method function callCommentservice() { try { // Comment Service Url var getCommentServiceUrl = self.commentsServiceUrl + self.getRating + "tenantId=" + self.tenantId + "&ratedObjectTypeId=" + sel ...

Can you explain the functionality of sinon's stub.yields method?

The explanation given in the documentation for sinon regarding stub.yields is as follows: By using stub.yields([arg1, arg2, ...]), you are essentially performing a function similar to callsArg. This will result in the stub executing the first callback it ...

Is it beneficial to utilize jQuery ahead of the script inclusions?

While working on a PHP project, I encountered a situation where some parts of the code were implemented by others. All JavaScript scripts are loaded in a file called footer, which indicates the end of the HTML content. This presents a challenge when tryi ...

What factors contribute to a one-hour discrepancy between two time stamps, deviating from the anticipated value?

Let's consider the dates '2022-04-01' and '2022-05-15'. When I calculated their deviation using Chrome devtools, here are the results: https://i.stack.imgur.com/tSZvk.png The calculated result is 3801600000. However, when my frie ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...

Modify a field within MongoDB and seamlessly update the user interface without requiring a page refresh

I am currently working on updating a single property. I have various properties such as product name, price, quantity, supplier, and description. When sending the updated quantities along with all properties to MongoDb, I am able to update both the databas ...

The requested resource at http://localhost/Grafica/%7Bd.icon%7D/ was not found (Error 404)

Creating a tooltip in a weather chart, I want to display an image of the sky condition. Below is the HTML code: <div id="tooltip"> <table class="table table-condensed"> <tr><th>Time (local)</th><th data-text="d ...

Update the WooCommerce shopping cart page automatically upon product removal

After trying to solve the issue of refreshing the cart page in WooCommerce when a product is removed, I came across this helpful question on Stack Overflow: Refresh the page after product remove from cart Woocommerce. Following the provided code snippet th ...

What would be the best way to structure this workflow as a JavaScript data format?

I have a complex workflow that I need to represent as a JavaScript data structure. This workflow involves a series of questions and answers where the response to one question determines the next one asked. Here is a basic example of what this workflow migh ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

Performing a count query with MongoDB Mongoose by grouping data based on multiple fields

I've developed an analytics API using MongoDB. Here is the model for my sessions: const sessionSchema = new Schema( { user: { id: Number, name: String, email: String }, }, { timestamps: true }, ); My goal is to calculate the number of uni ...

Fascinating CSS rendering glitch observed on zooming in: all browsers create a noticeable gap between containers except for Firefox

I'm experiencing a rather intriguing and peculiar issue with css styles when zooming in and out on the browser. Specifically, I've created a material ui card where the background-color changes upon clicking with an animation effect. The animati ...