Incorporating dynamic form elements using Vue.js within a targeted div

Here is the HTML and Vue.js code that I have:

<table class="table">
        <thead>
            <tr>
                <td><strong>Title</strong></td>
                <td><strong>Description</strong></td>
                <td><strong>File</strong></td>
                <td></td>
            </tr>
        </thead>
        <tbody>
            <tr v-for="(row, index) in rows">

                <td><input type="text" v-model="row.title"></td>
                <td><input type="text" v-model="row.description"></td>
                <td>
                    <label class="fileContainer">
                        {{row.file.name}}
                        <input type="file" @change="setFilename($event, row)" :id="index">
                    </label>
                </td>
                <td>
                    <a v-on:click="removeElement(index);" style="cursor: pointer">Remove</a>
                </td>


            </tr>
        </tbody>
    </table>

Upon clicking 'Add', a table row will be added to the table body

 <div>
 <button class="button btn-primary" @click="addRow">Add row</button>
 </div>

Below are the methods for adding or removing a row:

 methods: {
            addRow: function() {
                var elem = document.createElement('tr');
                this.rows.push({
                    title: "",
                    description: "",
                    file: {
                        name: 'Choose File'
                    }
                });
            },
            removeElement: function(index) {
                this.rows.splice(index, 1);
            },
            setFilename: function(event, row) {
                var file = event.target.files[0];
                row.file = file
            }
        }

If I were to use a custom div instead of a table, how can I add the dynamic form to a specific div? All examples that I've seen involve using createElement. Is there a way to add the dynamic form to a specific div with a unique id?

Answer №1

Here is my approach

The HTML structure

    <div id="app">
   <div id="appendsurface"></div>
                <div v-for="(row, index) in rows">

                    <p><input type="text" v-model="row.title"></p>
                    <p><input type="text" v-model="row.description"></p>
                    <p>
                        <label class="fileContainer">
                            {{row.file.name}}
                            <input type="file" @change="setFilename($event, row)" :id="index">
                        </label>
                    </p>
                    <p>
                        <a v-on:click="removeElement(index);" style="cursor: pointer">Remove</a>
                    </p>


                </div>
        <div>
            <button class="button btn-primary" @click="addRow">Add row</button>
        </div>
    </div>

After that, the JavaScript part

var app = new Vue({
            el: "#app",
            data: {
                rows: []
            },
            methods: {
                addRow: function() {
                
                    var elem = document.createElement('div');
                    elem.className= "uniqueclass";

                    document.getElementById('appendsurface').appendChild(elem);  
                
                    this.rows.push({
                        title: "",
                        description: "",
                        file: {
                            name: 'Choose File'
                        }
                    });
                },
                removeElement: function(index) {
                    this.rows.splice(index, 1);
                },
                setFilename: function(event, row) {
                    var file = event.target.files[0];
                    row.file = file
                }
            }
        });

You can view a live example on CodePen here

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

Unable to establish communication with server. Facing issues in connecting AngularJS with NodeJS

I am currently working on establishing a communication process between my server and client to receive either a "success" or "failure" response. The server is being developed using node.js with the express framework, while the client is built using angular ...

Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions? These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies? (function () { "u ...

How to retrieve the chosen option from a drop-down menu created within a loop in a React application

I am seeking guidance on the best way to create multiple drop-down menus (<select>) using a loop, so that I can retrieve their selected values using a button. I have attempted to replicate what is currently in my code, hoping this information is suff ...

Using npm as a build tool to merge files together

Upon discovering the flexibility of using npm as a task runner instead of gulp or grunt, I have successfully implemented various tasks such as linting, stylus processing, jade compilation, uglifying, and even watching files. However, I am facing difficulti ...

Building a simple messaging platform with the power of Socket.io and Node.js

After following the guide at http://socket.io/get-started/chat/, I attempted to create a basic chat application. However, upon running npm install --save socket.io I encountered the error message below. How can I resolve this issue? npm WARN package.jso ...

Using an array as the source for your Mui Autocomplete instead of JSON

I'm attempting to recreate the autocomplete MUI example shown here, but with a slight variation. Instead of utilizing a JSON data structure, I am simply passing an Array. Here is what I have tried: export default function SearchTutorialArray() { con ...

Guide to smoothly scroll to the top of an element containing collapsible panels using Jquery

I've encountered an issue with a series of divs that are set to toggle the state of a collapsible div upon clicking (similar to an accordion widget). The functionality works as intended, but I'm facing a challenge - I want the page to scroll to t ...

Display the outcome of a POST request on the webpage

Currently working with node.js/express and have a view that includes a form. This form POSTs to a route which returns JSON data. I want to be able to submit the form and display the returned data underneath the form on the same view without refreshing the ...

Incorporate a Vue directive based on a certain condition

Can a directive be set based on a condition? I have a directive called "sticky" that makes elements stick to the screen. I am currently using it in a social share component. <tempalte> <div class="social-share" v-sticky> .... ...

The Angular material datepicker is not accurately capturing the date I am trying to select

I am facing an issue with the Angular Material datepicker where it does not select the date I choose. Instead, in my AngularJS controller, I always get the sysdate even if I select another date. Can anyone help me figure out what I am doing wrong? Here is ...

Jquery and CSS3 come together in the immersive 3D exhibit chamber

Recently, I stumbled upon an amazing 3D image gallery example created using jQuery and CSS3. http://tympanus.net/codrops/2013/01/15/3d-image-gallery-room/ Excited by the concept, I attempted to incorporate a zoom effect (triggered every time a user clic ...

The Redux store has been modified, yet the changes are not reflected in the

In my Posts.js component, I am mapping every object in the posts array. Within this function, I attempt to filter all notes that have the same post_id as the id of the current mapped post object and store them in a variable called filteredNotes. I then pas ...

Tips for formatting the return Date when utilizing the setDate() method

I set the end of the week to be the upcoming weekend using the following code snippet this.weekEnd = new Date(this.currentDate.setDate(end)); Now, my goal is to update the weekEnd by adding 7 days to it. I attempted to achieve this as shown below, however ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

PHP is returning an empty response during an AJAX request

I am facing an issue with my AJAX request where I am trying to return a simple echo, but for some reason, it's not working this time. Even after stripping down the code to its bare essentials, the response is still blank. Javascript function getUs ...

Using JavaScript to transform JSON information into Excel format

I have tried various solutions to my problem, but none seem to fit my specific requirement. Let me walk you through what I have attempted. function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) { //If JSONData is not an object then JSON.parse will ...

Discovering the initial vacant row within an HTML table with Javascript

Below is a snippet of code that generates a table with 6 rows. The last two rows remain empty. The JavaScript logic in the code correctly determines and displays the total number of rows in the table. I'm currently looking for a way to identify the ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

The system cannot locate the "default" task. Please consider using the --force option to proceed. The process has been halted due to warnings

Below is the content of my gruntfile.js file var fs = require("fs"), browserify = require("browserify"), pkg = require("./package.json"); module.exports = function(grunt) { grunt.initConfig({ mochaTest: { test: { options: { ...

NodeJS experiencing a hitch in the image upload process

I am currently working on a Node code snippet that is used for uploading images. The images I am dealing with have sizes ranging from 10 to 200K, so they are relatively small in size. However, the issue I am facing is that Node seems to get stuck process ...