Retrieving values from all fields in a dynamic form using VuejsLet's say

In the process of developing an admin panel using Vuejs and tailwind CSS for managing exercises on a page, I have encountered some challenges.

My current objective is to insert the dynamic form values into a Firebase real-time database. However, I am struggling to extract the values from the form itself. The concept involves allowing users to add additional fields for each 'step' they wish to include in an exercise by clicking on a plus button next to the field.

I attempted to set a reference in the setup script: const step = reference([]);, but this method did not yield the desired outcome. I also explored adding it to the props, only to receive an error indicating that 'step' is not defined.

Outlined below is the setup script:

<script setup>
import { database, auth } from "../firebase";
import { ref, setWithPriority, push, set } from "firebase/database";
import { ref as reference } from "vue";
import router from "../router";

let exerciseRef = ref(database, "exercises/");
let selected = reference(null);

const props = defineProps([
    "selected",
    "name",
    "video",
    "summary",
    "description",
    "isActive",
]);

const emits = defineEmits([
    "update:name",
    "update:video",
    "update:description",
    "update:summary",
    "update:isActive",
]);

function createExercise() {
    exerciseRef = ref(database, `exercises/${selected.value - 1}/4`);

    set(exerciseRef, {
        name: props.name,
        video: props.video,
        summary: props.summary,
        description: props.description,
        isActive: props.isActive,
    });

    let logRef = ref(database, "logs/exercise/");
    let pushRef = push(logRef);

    setWithPriority(
        pushRef,
        {
            type: "added",
            exercise: props.name,
            admin: auth.currentUser.displayName,
            date: new Date().toLocaleString("en-US"),
        },
        0 - Date.now()
    );

    router.push("/admin/exercises");
}

This represents the HTML structure for the dynamic form:

            <form>
                <div class="form-group">
                    <label>Steps</label>
                    <div
                        v-for="(input, index) in stepNumbers"
                        :key="`stepInput-${index}`"
                        class="input wrapper flex items-center"
                    >
                        <input
                            v-model="input.step"
                            type="text"
                            class="h-10 rounded-lg outline-none p-2"
                            placeholder="Enter step"
                        />
                        <!--          Add Svg Icon-->
                        <svg
                            @click="addField(input, stepNumbers)"
                            xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 24 24"
                            width="24"
                            height="24"
                            class="ml-2 cursor-pointer"
                        >
                            <path fill="none" d="M0 0h24v24H0z" />
                            <path
                                fill="green"
                                d="M11 11V7h2v4h4v2h-4v4h-2v-4H7v-2h4zm1 11C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16z"
                            />
                        </svg>

                        <!--          Remove Svg Icon-->
                        <svg
                            v-show="stepNumbers.length > 1"
                            @click="removeField(index, stepNumbers)"
                            xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 24 24"
                            width="24"
                            height="24"
                            class="ml-2 cursor-pointer"
                        >
                            <path fill="none" d="M0 0h24v24H0z" />
                            <path
                                fill="#EC4899"
                                d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm0-9.414l2.828-2.829 1.415 1.415L13.414 12l2.829 2.828-1.415 1.415L12 13.414l-2.828 2.829-1.415-1.415L10.586 12 7.757 9.172l1.415-1.415L12 10.586z"
                            />
                        </svg>
                    </div>
                </div>
            </form>

Additionally, here is the script responsible for adding more fields to the form:

<script>
export default {
    name: "AddRemove",
    data() {
        return {
            stepNumbers: [{ step: "" }],
        };
    },
    methods: {
        addField(value, fieldType) {
            fieldType.push({ value: "" });
        },
        removeField(index, fieldType) {
            fieldType.splice(index, 1);
        },
    },
};
</script>

If you can provide any assistance or insights, it would be immensely appreciated.

Answer №1

To associate the input element using v-model to the "step" property of every object within the "stepNumbers" array, and when adding a new input, you include an object with a value property in the "stepNumbers" array, it is important to map the value to a single property.

I recommend reviewing this code snippet. https://codesandbox.io/s/serverless-brook-geii6z?file=/src/App.vue

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

Alter the class when $dirty occurs in Angular

I've recently started working with angular js and am attempting to incorporate animations into my login page. I have created a controller that will modify the class of the input field when clicked and when blurred. app.controller("con", function($sc ...

Determine which file to load based on the size of the browser

I have a quick question regarding the correct syntax. I am trying to only load the jQuery file if the browser screen width is less than 1100px. <script type="text/javascript"> $(document).ready(function() { if ($(window).width() < 1100) { ...

Tips for adjusting the language settings on a date picker

Is there a way to change the language from English to French when selecting a month? I believe I need to configure something in the core.module.ts. How can I achieve this? https://i.sstatic.net/Cpl08.png @NgModule({ declarations: [], imports: [ Co ...

Issue with Discord.js: Newly joined user's username appears as undefined

robot.on('guildmateEntry', person =>{ const greeting = new Discord.MessageEmbed() .setTitle(`Greetings to the realm, ${individual}!`) const room = person.guild.channels.cache.find(channel => channel.name === " ...

Ways to Randomly Flip Divs

I have developed an application where all divs flip vertically on hover. I am looking for a way to make the flipping random without requiring a hover. Any ideas on how to achieve this? .vertical.flip-container { position: relative; float: left; ma ...

Understanding how to retrieve a particular list item in JQuery without having the index in advance

I have a lengthy list that is broken down into various subheadings. How can I retrieve the second to last element of the list before a specific subheading, provided it is not the final element? Is it possible to do this if I know the ID of the subheading? ...

The click event for jQuery is failing to trigger on every link

Currently, I'm in the process of creating a "collapse all" button for the Bootstrap 3 collapsible plugin. It appears to be functioning correctly, but only when there is just one collapsible on the page. Once I add another one, the method only works on ...

Creating a mobile-friendly navigation bar with Vuetify for optimal responsiveness

I am attempting to utilize a vuetify tab component as my navigation menu in order to create a responsive navbar using vuetify. The goal is to have a normal navbar that functions like usual, but when viewed on a mobile device, it should hide the menu and di ...

Adding a break in a CardHeader element subtitle in MaterialUI using ReactJS

I have been working with older Material UI components (Version 0.20.1). Below is an excerpt of my code: return( <> <Card> <CardHeader actAsExpander={true} showExpandableButton={true} title = {user.name} ...

The API response in JSON format is displaying as "undefined"

My current code is running as follows: const request = require('request') const apiKey = 'XXXXXXXXXXXXXX' var dat; let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx' let qs = { q: '-34.48,150.92&ap ...

Allowing input fields to accept decimal numbers

I am currently facing an issue with an input field that is set to type=number, which does not allow for decimal numbers. However, I need to enable users to input decimal numbers but haven't been able to make it work. Would using regex be a possible so ...

What is the most effective method for disregarding undefined values?

Implementing a project using Vue.js and Vuex, I am retrieving data from an API that functions as a content-management system. The product class in the CMS possesses numerous properties that can be populated by the user, such as; { "title": &quo ...

Tips on invoking a class method within lodash debounce function

Help needed: Issue with TypeError - Expected a function at debounce when calling a class method in the lodash debounce class Foo { bar() { console.log('bar'); } } const foo = new Foo(); _.debounce = debounce(foo.bar(), 300); ...

Updating a list of books from a form in another component: Step-by-step guide

Hello everyone, I am fairly new to using React and am currently following a tutorial on creating a book library. In this project, I have an AddNewBook Component which is essentially a form structured as follows: function AddNewBook(){ const [name, setNam ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Tips for adjusting the angle in SVG shapes

I have designed an svg shape, but I'm struggling to get the slope to start from the middle. Can someone please provide assistance? <svg xmlns="http://www.w3.org/2000/svg" fill="none"> <g filter="url(#filter0_b_1_2556)"&g ...

What's the best way to make a popup link in my situation?

I'm attempting to use Angular to open a popup window in my situation. Here's what I've got: <a ng-href = "window.open('{{videoLink}}')" >open a video</a> When I try this, I get a 'Not found' error in the br ...

What is the best way to display a div box only when a user checks a checkbox for the first time out of a group of checkboxes, which could be 7 or more, and then hide the

Is there a way to make a div box appear when the user checks any of the first checkboxes? I have attempted using the following codes: JQ Codes: $('#checkbox').change(function() { if ($(this:first).is(':checked')) { cons ...

Prevent WordPress themes from running in order to integrate a personalized Vue.js front-end application

I'm currently working on a basic website that will utilize vuejs as the front-end framework and wordpress for generating dynamic content. To achieve this, I've placed wordpress inside the public directory of my vue project in a folder named app. ...

Ways to navigate private property using the App Component in Angular 4

I have successfully implemented code in my app component to retrieve the current URL and display it in app.component.html. app.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Compone ...