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

What methods can I use to retrieve traversed objects using riak-js?

Utilizing Node with riak-js to interact with a Riak database. I have established two buckets named invites and events. The invites bucket contains a link to events. Is there a way to fetch both the invite object and the corresponding event object in one qu ...

Sending text from a Tinymce textarea using Laravel 4.2

I am currently facing an issue with a form that includes a tinymce textarea, allowing users to edit text and save it into a database with HTML tags for display on their profile. The problem arises when Laravel 4.2 escapes the HTML tags, making it difficult ...

Utilizing jQuery.ajax to Send an Array of Objects to a PHP Function

In this scenario, an array of objects is represented as follows: rectangle[0].width = w; rectangle[0].height = h; rectangle[1].width = w; rectangle[2].height = h; rectangle[3].width = w; rectangle[3].height = h; ... We need to figure out how to send thi ...

Utilizing various colors for tooltipFontColor in Chart.js

I'm trying to customize the font color for tooltip labels in Chart.js, but I want to set different colors based on certain conditions. Specifically, I want the label color to be white by default, but change to red if a condition is met. I've look ...

Tips for implementing autocomplete functionality in AngularJS input fields

I attempted to integrate code from a website (http://jsfiddle.net/sebmade/swfjT/) into my program, but unfortunately, the output did not match what was expected. I am also looking to implement a search function by camera id. Can anyone provide assistance? ...

"Learn how to position a div element below the header div and above the footer div while maintaining full height in

Recently delving into the world of reactjs, I find myself facing a challenge with a page that contains 3 distinct blocks formed by divs. Have a look at the layout on my page: My Page This is the code snippet I have worked on: return ( <div> ...

Is it safe to securely store connection credentials in javascript?

I am currently working on developing a web chat app for a Minecraft server using this API. However, the demo script I am referring to displays connection information in plain text, making it easily visible to any client's computer. Is there a way to s ...

Having issues with inline conditional statements in Angular 5

There is a minor issue that I've been struggling to understand... so In my code, I have an inline if statement like this: <button *ngIf="item?.fields?.assetType !== 'tool' || item?.fields?.assetType !== 'questions'">NEXT< ...

Struggling to integrate vue js into Laravel

I recently developed a character counter feature for SEO input fields using Vue JS. It functioned flawlessly on jsfiddle, however, upon integrating it with Laravel, I encountered an issue. Instead of displaying the number of characters remaining, it showed ...

The Google Docs viewer is displaying an empty screen

I have been utilizing the Google Docs viewer on my website: <div class="embed-r embed-responsive-a"> <iframe class="embed-responsive-it" src="https://docs.google.com/viewer?embedded=true&amp;url=http://LINK.PDF"></iframe> </div& ...

Are you experiencing issues with your Ajax request?

I've been struggling to retrieve json data from an API. Despite my efforts, the GET request seems to be executing successfully and returning the correct data when I check the Net tab in Firebug. Can anyone offer advice on what could be going wrong or ...

Adding event listeners for elements inside slots in Vue.js: A step-by-step guide

I need to create a unique vue component called "characters-counter" that can accurately count the characters in input elements, as shown below: <characters-counter v-slot =" {charactersCount} "> <div>{{ charactersCount }} Chars< ...

Can SailsJS be used exclusively for API processes?

Can SailsJS be used solely as an API? After downloading the Sails project, is it possible to exclude the views and focus only on utilizing Sails as an API? ...

Secondary Form Checkbox Input

Presently, I am working with a dynamic form-checkbox input element. <b-form-group label="Skills"> <b-form-checkbox-group v-model="form.selected" :options="options"/> </b-form-group> However, I am looking to enhance this functionalit ...

Tips for accessing the 'styled' function in Material UI ReactHow to utilize the 'styled' function

Hey there, I'm facing an issue while trying to export a styled AppBar. Check out my code below: import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import MuiAppBar from '@mui/material/AppB ...

React and SASS - issue with checkbox component not being properly aligned with its label

I'm brand new to React and I'm currently in the process of converting a pure HTML page into a React component. How can I adjust the SASS stylesheet to match the original HTML layout? Here is my current React setup (the checkbox displays on the r ...

Tips for shortening extra text in a non-wrapping HTML table cell and adding "..." at the end

My HTML template includes text imported from a database field into a <td> tag. The length of the text can range from 3 to 200 characters, and the <td> spans 100% of the screen width. If the text surpasses the width of the screen, I want it to b ...

Retrieving JSON Arrays in PHP through an AJAX Request

Having trouble extracting data from multiple arrays in an AJAX request. Can anyone help? Here's what I'm trying to send: https://i.stack.imgur.com/4MEL4.png Executing a jQuery AJAX POST to a PHP file, but uncertain how to retrieve the data. An ...

What is the method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

What is preventing me from accessing the props of my functional component in an event handler?

I've encountered a strange issue within one of my components where both props and local state seem to disappear in an event handler function. export default function KeyboardState({layout, children}) { // Setting up local component state const [c ...