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

Incorporating a Link into a Radio Button component in Material-UI using react-router

Greetings! I have two radio buttons and would like to include a link. I attempted to achieve this in the following manner: <RadioButton value="/searchByArtistAndName" label="Artist and Name" style={styles.radioButton} contai ...

Transforming all numbers to a consistent scale with the help of Numeral JS

Is there a way to customize the output of the numeral.js function so that it always returns numbers in thousands? For example, converting 1000000 to 1000k and 100 to 0.1k. console.log( numeral(1000000).format('0a') ); <script src="https ...

Difficulty with Vue.js updating chart JS label names

I have been working with Vue JS and implementing a chart in my single page application. However, I am encountering difficulties updating the Legend and despite numerous attempts and searches, I am unable to get it to update. Any assistance in correcting my ...

Reload the Node.js webpage

Is there a method to automatically refresh a Node.js page following a socket.io event? var messageDynamic = "Initial status"; app.get("/", function(request, response) { response.setHeader('Content-Type', 'text/plain'); respons ...

Update a nested object key by concatenating key names with "." to create a string

Imagine having this specific object structure: var obj = { level1 :{ level2: { level3: { title: "champion" } } } } Now the goal is to update the title key using a provided string (note that it's a string, not an actua ...

Remove child elements in Jquery that do not match the specific numbers saved in the array

I've got this array: var numbersArray = [1, 2, 4, 5] and also an unordered list in HTML <ul> <li> item 1 </li> <li> item 2 </li> <li> item 3 </li> <li> item 4 </li> <li> item 5 ...

Utilize Hardhat and NPM to distinguish between unit tests and integration tests efficiently

Struggling with setting up two commands in my package.json for running unit tests and integration tests. I am having trouble defining the location of the testset for each type of testing. Within the scripts section of my package.json, I have created two c ...

Why JSON.parse is unable to determine if the argument is already in JSON format

When using JSON.parse, it typically parses a stringified JSON. However, if a variable is already in the form of JSON and you attempt to parse it with JSON.parse, an error is thrown: > a [] > a = JSON.parse(a) SyntaxError: Unexpected end of input ...

Optimizing your approach to testing deferred always

When creating test cases for code within a jQuery AJAX call's always method or in bluebird promises' finally function, it often involves the following structure: function doStuff() { console.log('stuff done'); } function someFunct ...

Exploring First-Person Shooter Rotation with THREE.JS

I recently attempted to create a rotation system for a First Person Shooter game using THREE.JS. However, I encountered a strange issue where the camera would pause momentarily before returning, especially at certain rotations. When checking the rotation ...

Vue.js and Inertia will wait for all synchronous setups to be completed before rendering the page

My navigation menu is dynamically created server-side and displayed on the client side through async setups and the suspense API. With Inertia providing this data upon each page load, the navigation must be rendered again whenever I navigate to a new page, ...

ajax ignores output from php

I've been working on passing PHP echo values through AJAX, but I've encountered a problem where the if and else conditions are being skipped in the success function of AJAX. Even when the if condition is met, the else statements are still being e ...

Creating a replicated Dropdown menu with Jquery and inserting it into a changing Div

I currently have a dropdown list on my page with the ID of "mainDDL" and some pre-existing data. Now, I am looking to duplicate this dropdown list and add it to another specific div element. To accomplish this, I used the following code snippet: var dd ...

Utilize Google Autofill to easily populate address fields in a form

I've come across several autofill address codes, but I'm looking to integrate a Post function that would allow me to post the obtained data to a PHP page. Is there anyone who can assist with the javascript or HTML code to achieve this? HTML Cod ...

Click the button to reset all selected options

<form method="post" action="asdasd" class="custom" id="search"> <select name="sel1" id="sel1"> <option value="all">all</option> <option value="val1">val1</option> <option value="val2" selected="selected"> ...

Having trouble installing npm package in Angular project

After cloning my project from GitLab, I encountered an issue while trying to install the NPM packages. When I ran npm install, an error popped up: https://i.stack.imgur.com/WNT5s.png Upon checking the log file, I found the following error message: 3060 ...

Utilizing Ajax technology to load script in Tapestry 5

I have two components, a "DirectoryViewer" and a "MediaViewer", that I created. The Directory Viewer displays a list of file names and contains a MediaViewer component to show the selected file. This setup is functioning properly. Within the DirectoryView ...

Is there a way to incorporate a computed value into a table prop while working with Element UI?

In my frontend development, I am utilizing vuejs along with element ui. I am faced with the task of rendering a table that includes dates in unix format. To make these dates more user-friendly, I have incorporated moment.js to convert them into a readable ...

Choosing the right framework for a web application

Currently, I am at a crossroads when it comes to deciding on the architecture of the web application I will be developing. As part of a small team, I am tasked with working on this project solo while my colleagues focus on other tasks. The front-end of th ...

One set of objects is active in retrieving data, while the other remains inactive

I'm working with an array of objects and here is what it looks like: const default_apps = [ { 'post_title': 'Excel', }, { 'post_title': 'Word', }, { 'post_title': 'SharePoi ...