utilizing dropzone.js to pass an index and invoke a function

While everything seems to be functioning correctly, there is a notable issue that I am facing. When I upload an image to my Dropzone instance, I want the file name of that image to be added to the cards array under imageInfo.

The challenge lies in figuring out how to invoke an independent function through Dropzone.

In particular, what I need to solve here is how to call my imageChange function with both the file from Dropzone and the card as it's within the loop.

Is there a way to trigger that function with both attributes when adding an image?

new Vue({
      mixins: [VueClickaway.mixin],
      components: {},
      el: "#commonNameDiv",
      data() {
        return {
          searchString: [''],
          results: [],
          savedAttributes: [],
          cards: [],
          showList: false,
          zoneNumber:[],
          imageZoneNames: [],
          imageInfo: [] 
        }           
      },
      methods: {
        imageChange(file){
            console.log('it worked');
        },
        autoComplete(ev, card) {
          this.results = [];
          console.log(this.searchString);
          if (ev.target.value.length > 2) {
            axios.get('/product/parts/components/search', {
              params: {
                searchString: ev.target.value
              }
            }).then(response => {
              card.results = response.data;
              this.showList = true;
              console.log(this.results);
              console.log(this.searchString);
            });
          }
        },
        saveAttribute(result, card) {
          card.value = result.attribute_value;
          card.results = [];
          card.zone = this.zoneNumber;
          this.showList = false;
        },
        addCard: function() {
            this.cards.push({
              index: "",
              value: "",
              zoneNumber: "",
              results: [],
              componentImage:"",
              imageInfo: ""
            });
            
             // Index of the last card pushed
            let cardIndex = this.cards.length - 1;
            let instance = this; // $vm
            Vue.nextTick(function () {
              new Dropzone("#dropzone-"+cardIndex, {
                maxFilesize: 12,
                renameFile: function (file) {
                    var dt = new Date();
                    var time = dt.getTime();
                    return time + file.name;
                },
                acceptedFiles: ".jpeg,.jpg,.png,.gif",
                addRemoveLinks: true,
                timeout: 50000,
                removedfile: function (file) {
                    console.log(file.upload.filename);
                    var name = file.upload.filename;

                    var fileRef;
                    return (fileRef = file.previewElement) != null ?
                        fileRef.parentNode.removeChild(file.previewElement) : void 0;

                },
                init: function() {
                    this.on("addedfile", 
                    function(file) { 
                        instance.imageZoneNames.push({name: file.upload.filename});
                        console.log(file);
                        console.log(instance.imageZoneNames);

                    });
                }
            });
            });

            console.log('cards here');
            console.log(this.cards);
        },
        hideDropdown() {
          this.showList = false;
        },

      },
      created() {

        let instance = this;

        Dropzone.autoDiscover = false;
      

        this.addCard();

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


<div id="commonNameDiv">
<div class="uk-grid" v-for="(card, i) in cards" :key="i">
                <div class="uk-width-1-10"  >
                    <input v-model=" card.zoneNumber" size="4" type="text" name="mapNumber">
                </div>
                <div class="uk-width-6-10">
                    <input
                      style="width:100%"
                      placeholder="what are you looking for?"
                      v-model="card.value"
                      v-on:keyup="autoComplete($event, card)"
                    >
                    <div v-if="showList" v-on-clickaway="hideDropdown" class="panel-footer componentList" v-if="card.results.length">
                      <ul>
                        <li  v-for="(result, i) in card.results" :key="i">
                          <a v-on:click="saveAttribute(result, card)">@{{ result.attribute_value }}</a>
                        </li>
                      </ul>
                    </div>
                </div>
                <div class="uk-width-3-10">
                    <form v-on:change="imageChange(card)" method="post" action="{{url('product/parts/upload/store')}}" enctype="multipart/form-data"
                          class="dropzone" v-bind:id="'dropzone-'+i" v-model="card.imageInfo">
                    </form>
                </div>
            </div>

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

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

Answer №1

The `addCard` function already has access to the specific `card` being added to the collection of `cards`, so it is possible to pass that `card` object into the callback for the `addedfile` event. As an example, you could include a `filename` property in each `card` object, and then update this property within the `addedfile` callback using information from the `file` event argument:

export default {
  methods: {
    addCard() {
      //...

      const card = {
        //...
        filename: '',
      }
      this.cards.push(card)

      new Dropzone('#dropzone', {
        init() {
          this.on('addedfile', file => {
            card.filename = file.upload.filename
          })
        }
      })
    }
  }
}

Check out the code snippet on CodePen.

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

The functionality of ClickMarker is malfunctioning in the XY Amcharts

Recently, I encountered a situation where I had to incorporate custom legends in XY Amcharts. After managing to implement them successfully, I came across an issue. Despite adding event listeners to the legends, the associated function failed to trigger. ...

Guide to incorporating external CSS and JavaScript into an Angular 2 project with Express.js and Node.js

As a newcomer to Angular2 and NodeJs, I am eager to learn how to integrate external CSS and JS in an Angular2 and Nodejs express app. Specifically, I am looking to integrate a bootstrap admin theme into my Nodejs application. The screenshots below provide ...

Manipulate an object in Three.js using the ObjLoader functionality

I'm currently working on manipulating an object loaded using OBJLoader in Three.js. The issue I'm facing is that while it's easy to manipulate the object once, I can't figure out how to do so during the animate loop or anywhere outside ...

The basic jQuery script seems to be malfunctioning

I am trying to attach an on click event to an li element using jQuery. I have written a simple jQuery code within the document ready function, but for some reason it is not functioning as expected. I have checked in both Chrome and Firefox, and there are n ...

JavaScript code that activates several hovering elements

I am a beginner in the world of JavaScript and I'm attempting to create a simple function that will activate multiple div hover effects. I have tried various approaches so far, but I believe this code is closer to the solution. Any assistance from som ...

What is the best way to send props to a React component?

Sorry for the inconvenience of asking for help with finding an issue in my code, but I'm facing challenges while learning React. I am attempting to pass a variable named hashRoute to a component in react. However, every time I try to access the prop ...

What is the best way to use jQuery to increment the number in an input field by a specific value?

My goal is to utilize jQuery to increment a number in an input field and then display the updated value in the same input field. The specific id of this input field is "total". Here's my attempt so far: function addBag(){ var bagprice = 79.99; ...

jQuery does not function properly when used with string variables

Why am I experiencing different results in Google Chrome when using a hard-coded string versus storing the same string in a variable? While the hard-coded string works properly, the same string stored in a variable does not produce the expected outcome. ...

Using ES6, when utilizing array map in ReactJS, the function does not produce a return value

One challenge I'm facing involves mapping an array to find a specific string value. Unfortunately, despite my efforts, the map function is not returning anything as expected. class Application extends React.Component { constructor(){ super(); ...

Showing exclusively JavaScript data in a select element

I am struggling with getting a select tag to display only JavaScript values. Here is the code snippet: <select id="pname"> <option>som data</option> </select> After running a JavaScript function, I want to update the select ta ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...

What is the best way to delete a model from a Backbone.Collection?

How can I properly remove a model from a collection in Backbone.js? var item = new Backbone.Model({ id: "01", someValue: "blabla", someOtherValue: "boa" }); var list = new Backbone.Collection([item]); list.get("01").destroy(); After calling ...

Troubleshooting Safari's Issue with onclick() Functionality

I encountered an issue where the code was working perfectly on IE7 but not on Safari (5.0.5). I would like to find a solution without relying on jQuery. The ultimate goal is for this functionality to work seamlessly on iPad, but currently, I am testing it ...

AngularJS encountered an error while attempting to load a template: [$compile:tpload]

After developing my angularjs example app in my netbeans ide based local server, I encountered an issue when I tried to move the application to an nginx server. The browser displayed the following error message: Error: [$compile:tpload] Failed to load tem ...

How can you iterate over the input elements that are currently visible within a form using Javascript?

Is there a way to clear the values of all visible input fields in a form using JavaScript? I'm currently struggling with setting text inputs to empty as they come out as undefined. Any suggestions on how to achieve this? ...

Issue with CSV download box not showing up on Rails version 2.3.11

I've encountered an issue while trying to export a csv file with some data. I am using ajax call to select rows from the view table (jqGrid) and export them in a csv format. However, after a successful ajax call, the filtered data is displaying as an ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...

How can a string be transformed into a JavaScript Object without using JSON?

I have a good grasp on parsing a valid JSON string using JSON.parse('{"key" : "value"}'). But what happens when dealing with a valid JS object, but invalid JSON, such as: JSON.parse("{ key : 'value'}")? The outcome of this example is a ...

You are unable to define a module within an NgModule since it is not included in the current Angular compilation

Something strange is happening here as I am encountering an error message stating 'Cannot declare 'FormsModule' in an NgModule as it's not a part of the current compilation' when trying to import 'FormsModule' and 'R ...

create a recurring design wallpaper within the TinyMCE editor

One of my functions alters the background of the tinymce editor. However, I am interested in having a wallpaper repeat in a similar fashion to background-repeat: repeat; in CSS. How can I achieve this? Here is the function: function SettinymceImage(bg_i ...