The parameters for Vue.js @change events are consistently returning as 0 whenever a file is uploaded by clicking on the picture

Check out my JSFiddle here:: https://jsfiddle.net/includephone/o9gpb1q8

I've encountered an issue involving the @change event on an input field. My goal is to create a carousel of images with 4 images per slide.

Data Object Structure

 data: function () {
        return {
            page: [
                {
                    type: 'text',
                    name: 'title-brand',
                    text: '',
                    image: '',
                    preview: ''
                },
                {
                    name:'slider',
                    type:'file',
                    slide:[
                        [
                            {
                                model_name:'',
                                inst:'',
                                item_name:'',
                                item_link:'',
                                image:'',
                                preview:''
                            },
                            {
                                model_name:'',
                                inst:'',
                                item_name:'',
                                item_link:'',
                                image:'',
                                preview:''
                            },
                            {
                                model_name:'',
                                inst:'',
                                item_name:'',
                                item_link:'',
                                image:'',
                                preview:''
                            },
                            {
                                model_name:'',
                                inst:'',
                                item_name:'',
                                item_link:'',
                                image:'',
                                preview:''
                            }
                        ]
                    ],
                }
            ]
        }
    },

Methods I'm Using

methods: {
        onImageChange(e, parent_index, index, item_index){
            let files = e.target.files || e.dataTransfer.files;
            let vm = this.page[parent_index];
            console.log(`${index}, ${item_index}`);
            let reader = new FileReader();
            reader.onload = (e)=> {
                Vue.set(vm.slide[index][item_index], 'image', e.target.result);
            }
            Vue.set(vm.slide[index][item_index], 'preview', URL.createObjectURL(files[0]));
            reader.readAsDataURL(files[0])
        },
        stat(par1, par2){
            console.log(`pat1: ${par1}, par2: ${par2}`);
        }
}

Template for Data Display

<div v-for="(component, parent_index) in page" v-bind:key="parent_index" class="container-constructor">
    <div v-if="component.name==='slider'" class="data-block slider">
        <div class="body-block">
            <div v-for="(slide, index) in component.slide" v-bind:key="index">
                <div v-for="(item, item_index) in slide" v-bind:key="item_index" class="slider-item">
                    <button type="button" @click="stat(index, item_index)">Click {{index}} {{item_index}}</button>
                    <label for="slider-item-file-1">
                        <img v-if="item.preview.length>1" :src="item.preview" width="160px" height="200px"/>
                        <img v-else src="images/image6.png" width="160px" height="200px"/>
                    </label>
                    <input type="file" @change="onImageChange($event, parent_index, index, item_index)" id="slider-item-file-1"/>
                    <div class="slider-item-info">
                        <input type="text" v-model="item.model_name" name="model-name" placeholder="model name"/>
                        <input type="text" v-model="item.inst" name="instagram-model" placeholder="model inst"/>
                        <div class="item-name">
                            <input type="text" v-model="item.item_name" name="item-name" placeholder="item name"/>
                            <input type="text" v-model="item.inst" name="item-link" placeholder="item link"/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Has anyone experienced issues with passing parameters correctly, as mine always seem to be 0 when loading? Any insights on how to resolve this?

Answer №1

The issue with item_index always being 0 stems from the fact that the label assigned to the image is tied to the generic id slider-item-file-1, which is applied to every file input element. To resolve this, each element should have a unique id. Currently, your code lacks this uniqueness, causing the click on the label to target the first occurrence of that id in the document body, resulting in item_index consistently returning as 0. Modifying the ids dynamically can rectify this dilemma.

This explains why clicking on the bottom image causes it to jump to the top of the page - it navigates to the initial file input with the specified id.

<label :for="'slider-item-file-' + parent_index + '-' + index + '-' + item_index">
      <img v-if="item.preview.length>1" :src="item.preview" width="160px" height="200px"/>
      <img v-else src="images/image6.png" width="160px" height="200px"/>
</label>
<input type="file" @change="onImageChange($event, parent_index, index, item_index)" :id="'slider-item-file-' + parent_index + '-' + index + '-' + item_index"/>

Each id will now include the corresponding index value from the for loop.

I trust this provides clarification.

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 is the best way to showcase a JSON object in an attractive format on a webpage?

Similar Question: JavaScript data formatting/pretty printer var theobject_string = '{...}'; // I have a JSON object as a string. Is there a way to present this string in a visually appealing manner on an HTML webpage? I would like the ...

Unable to display ChartJs within the same DIV on the webpage

I'm struggling to display the Pie Chart from ChartJs in the correct DIV when I click from the left DIV. Running the chart directly works fine, but I want them both on the same page in separate DIVs. I have separate HTML files for each link and they wo ...

Refreshing a Next.js website on-demand using the Django model's save function

My current setup involves a next.js website deployed on Vercel, which retrieves data from an API provided by Django. Utilizing a new feature in Next.js known as Incremental Static Regeneration On-Demand, I am able to rebuild specific pages without having t ...

"Retrieve an image source using a jQuery Ajax call and swap it on

I am working on a webpage that includes an <img src="..." /> tag with a default src set. My goal is to use jQuery to make an ajax request to fetch another image, and only once this new image has fully loaded, update the src attribute of the <img ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Tips for utilizing the useContext hook in Next.js

I'm facing an issue with persisting information between different pages using nextjs and the useContext hook. Despite changing a variable in one page, it reverts back to its default value when navigating to another page. Below is a glimpse of the dir ...

Positioning tooltip arrows in Highcharts

I'm attempting to modify the Highcharts tooltip for a stacked column chart in order to have the arrow on the tooltip point to the center of the bar. I understand that I can utilize the positioner callback to adjust the tooltip's position, but it ...

Troubleshooting issue with Django forms and JavaScript interactions

For the past day, I've been grappling with a particular issue and haven't made much progress. My setup involves using a django inline form-set, which displays all previously saved forms along with an additional empty form. To show or hide these f ...

Verify if there is a value in at least one of the multiple input fields

I have 4 input fields and I need to check if at least one of them has a value. If none of them are filled out, I want the function to stop. Below is the current code snippet I'm using but it's not working as expected because it doesn't ente ...

Breaking free from JavaScript snippet within a PHP function in WordPress

There seems to be an issue with a function within one of the PHP files on a WordPress website. It appears that there may be an error related to escaping multiple quotes and slashes. Here is the specific line of code causing trouble: echo '<script ...

A step-by-step guide to accessing Chrome performance metrics using JavaScript

By utilizing Chrome Dev Tools, I am able to perform the following actions: Begin by opening Chrome Dev Tools (simply right click on any page in Chrome and select "inspect") Navigate to the "performance" tab Click on the record button Interact with a butt ...

What is the correct way to outline the parameters for deactivating functions?

Request for Assistance! I am facing a challenge with multiple blocks in my WordPress website. Each block contains a checkbox, two select options, and an element that needs to be toggled based on the selected options in the dropdowns. The functionality to ...

Having trouble accessing a DOM element within a Vue component while using vanilla JavaScript

I am attempting to dynamically update data from a Vue component using jQuery in a Webpack project. Below is the code snippet: <template> <div id="container"> <slot>show string!!</slot> <div id="s_container"&g ...

Issue with Angular controller failing to load when link is clicked

I am currently developing a webpage that incorporates Angular and responds to ajax requests by populating data into a table. When I manually enter the address, everything works as expected. However, if I navigate to the page using a link ( <a href="/pro ...

Searching through the use of autocomplete with alternative parameters

In the example below, - https://codesandbox.io/s/g5ucdj?file=/demo.tsx I am aiming to achieve a functionality where, with an array like this - const top100Films = [ { title: 'The Shawshank Redemption', year: 1994 }, { title: 'The Godfa ...

Steps for inserting new rows into a table from text fields1. Begin

As someone who is brand new to jquery/html, I am eager to create a diary specifically for logging my long distance running times in a neat table format. Here's the HTML code I have been working on: <head> <title>Running Diary</titl ...

jqueryajax function returns a boolean value upon completion

Recently, I developed a container method to handle an ajax request: function postRating(formData) { $.ajax({ type: "POST", url: '/api/ratings', data: formData }) .done(function () { return true ...

What is the process for accessing an API that requires a token using Axios in a Vue.js application?

I am trying to retrieve information from an API that has a JSON file using Axios, but it requires a Token and I am unsure of how to properly implement it. Can anyone provide assistance with this? The API can be accessed here: ‫‪https://api.nytimes.com ...

Integrating individual front end JavaScript files into an Express.js application

I've been working on a JavaScript file that contains over 200 lines of code for the front end logic of my project. It handles interactions like button clicks, image displays, and more, similar to a game. However, I'm struggling to figure out how ...

Download the browser version of UglifyJS 2 now

Is there a way to download the browser version of UglifyJS 2 without having to build it myself? I'm running into issues with the manual installation. I used npm to install uglify-js, but I can't seem to find where to execute the uglifyjs --self ...