Organizing form data using Vue

One of the features of my code is the ability to create dynamic input and select elements:

<div v-for="(index) in rows">
    <select>
        <option selected="true" disabled>Select Type</option>
        <option>Name</option>
        <option>Address</option>
        <option>Email</option>
        <option>Phone</option>
        <option>Medical</option>
        <option>Tax File Number</option>
        <option>Card Number</option>
        <option>Financial Card</option>
        <option>Medical Card</option>
        <option>Social Card</option>
    </select>
    <input type="text" list="predictive_data" class="uk-input">
</div>

<button v-on:click="addRow" type="button">Add Input</button>

While this setup works well, I face a challenge in organizing the inputs. I'd like to group them together for better clarity. For instance, if there are multiple names and emails, it would be helpful to distinguish whose data belongs to whom when sent to my Flask backend.

Currently, when I add 3 names and 1 email, the data reaches my backend in this format:

Name:['John Smith', 'Jane Doe', 'Bob Alan'], Email:[<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e2d21212225272a78770e2b232f2722602d2123">[email protected]</a>]

To improve this, I prefer the data to be structured like this:

{Name:'John Smith'}, {Name:'Jane Doe', Email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d4d8d8dbdcded3818ef7d2dad6dedb99d4d8da">[email protected]</a>'}, {Name:'Bob Alan'}

Answer №1

When it comes to HTML form encoding (

application/x-www-form-urlencoded
), it's important to note that arrays of objects are not supported in the standard format. While frameworks like Laravel or Rails provide ways to handle complex objects through special key-naming in form data, Flask does not offer this out of the box.

In order to work around this limitation, I suggest having the Vue client send the form data in JSON format as per the desired structure. Consequently, the Flask backend should then receive and process this data as JSON using request.get_json() instead of request.form.

  1. One solution is to break down your groups into individual rows, where each row comprises a label and value that are bound to <select>.v-model and <input>.v-model respectively:

    // MyForm.vue template
    <fieldset v-for="group in groups" :key="group.id">
      <div v-for="row in group.rows" :key="row.id">
        <select v-model="row.label">...</select>
        <input type="text" v-model="row.value">
      </div>
      <button type="button" @click="addRow(group)">Add Input</button>
    </fieldset>
    
    // MyForm.vue script
    data() {
      return {
        groups: [
          {
            id: 1,
            rows: [{ id: 1, label: "Name", value: "John Doe" }]
          },
          {
            id: 2,
            rows: [
              { id: 2, label: "Name", value: "Jane Doe" },
              { id: 3, label: "Email", value: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e7d71717275777a28275e7b737f7772307d7173">[email protected]</a>" }
            ]
          },
          {
            id: 3,
            rows: [{ id: 4, label: "Name", value: "Bob Alan" }]
          }
        ]
      };
    }
    
  2. Implement a submit method to handle the posting of your specially formatted data:

    // MyForm.vue script
    methods: {
      submit(e) {
        const formData = this.groups.map(group => group.rows.reduce((c, row) => {
          c[row.label] = row.value;
          return c;
        }, {}));
    
        axios.post(e.target.action, formData);
      }
    }
    

Check out the demo

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

Having trouble retrieving the ID of the clicked element in AngularJS?

I have successfully implemented a function in angularjs to retrieve the id of the clicked element. Below is my code snippet html <a href="#faqinner/contactform" class="clearfix" ng-click="getCateId($event)" id="{{option.id}}"> <span class= ...

Customizing multi select in MUIv5 AutoComplete feature

My current challenge involves using the mui Autocomplete multi-select component. I'm having trouble getting it to function according to my specific requirements. Essentially, I need to set default selected values passed as props from the Parent compon ...

The route function is not being executed

I'm currently developing a straightforward restaurant web application that utilizes a mongo-db database to manage the menu items. The problem lies with my client js file, which is supposed to utilize a routing function to access the database and retri ...

Strategies for capturing POST data sent to a JavaScript webpage

The request is sent from an external source beyond my control xyz.php <form action='https_:_//xyz.com/javascriptFile' method='POST'> <input type='text' name='data' /> </form> to: (My custom f ...

Generate a new entry by analyzing components from a separate array in a single line

I have a list of essential items and I aim to generate a record based on the elements within that list. Each item in the required list will correspond to an empty array in the exist record. Essentially, I am looking to condense the following code into one ...

Display a modal before leaving the page?

I need to display a modal message when a user navigates away from the page, triggered by a successful AJAX call. The issue is that if the message loads too quickly, the user may not have enough time to read it before being directed to another page. This is ...

What is the best way to make a vertical line using the CSS code provided in the link?

Check out this cool horizontal line design I found on stackoverflow: Click here for CSS code to create the line I really like the look of the line. Here's how I implemented it on my website: hr.fancy-line { border: 0; height: 5px; } hr ...

The images in my gallery refuse to hover or respond to my clicks

Ever since integrating this cropping effect (http://jsfiddle.net/BPEhD/2/) to my gallery images, I've encountered an issue - the hover state is missing and I can't click on the images either. Although the pointer cursor appears when I hover over ...

Conceal the parent div from its sibling within the same parent container

My goal is to conceal a parent component from its child element. I attempted to achieve this by using the parent component as a background while adding additional backgrounds to the child elements for overriding purposes. However, this method did not work ...

Ways to disable the caching feature in Google Chrome

When I am working on CSS and JS around a page, I need to disable the cache mechanism in Google Chrome browser. A trick is to open Chrome DevTools, which automatically disables the cache mechanism (you can configure this in the settings section). Are ther ...

Best Practices for Managing Asynchronous Updates in Angular Controllers

Let me explain my current setup -- I have a controller that utilizes a service to perform some tasks and then fetches data asynchronously. Right now, the data is returned after a timeout, but ideally it would involve more complex operations: This is how m ...

Enhancing User Experience with Load Indicator during State Changes in React Native

I'm facing an issue where the page for displaying a single item is loading slowly - I need to delay the page from loading until the object has changed. After checking the navigation params through console log, I can see that the id changes when each b ...

Ways to insert additional panels prior to and after a selected panel

A button is provided in the report designer detail band that, when clicked, should add new panels immediately before and after the detail panel. $parentpanel = $this.parents(".designer-panel:first"); This code snippet is used to locate the parent panel u ...

Injecting CSS styles into the head tag dynamically with jQuery from within the body of a

When it comes to adding CSS to the head of an HTML page from the body using JavaScript and jQuery, I have come across two methods. One involves using jQuery to directly append the CSS to the head, while the other method involves creating a style element an ...

Iterate over an array in JavaScript and include the elements as parameters in an SQL query

Can I set an SQL string to a variable in JavaScript and populate part of it by looping through an array? Here is the initial SQL: var tag = ["fun", "beach", "sun"]; var sql = "SELECT * FROM myTable " +"WHERE id > 5" //... // L ...

Utilizing titanium to develop a functionality that listens for button presses on any area of the screen

I am trying to simplify the action listener for 9 buttons on a screen. Currently, I have individual event handlers set up for each button, which seems inefficient. Is there a way to create an array of buttons and manipulate them collectively? For example ...

Improved method for retrieving a subtask within a personalized grunt task?

As someone who is just starting out with Grunt and has only created a few custom grunt tasks, I've come up with what might be seen as an unconventional solution for traversing the initConfig to subtasks. My approach involves putting together a regex a ...

Changing the Month Label Format from Short (MMM) to Long (MMMM) in Angular Material Datepicker

I am looking to customize the month labels in Angular Material datepicker. By default, the month view displays in MMM format and I want to change it to MMMM using custom MatDateFormats. export const APP_DATE_FORMATS: MatDateFormats = { parse: { dat ...

When using Next.js revalidate, an error may occur stating: "There are keys that require relocation: revalidate

I have been attempting to utilize the revalidate function in my code by following the example provided by Vercel. However, I keep encountering an error. Here is the snippet of code that I am currently using: export async function getServerSideProps() { c ...

Tips for implementing a distinct texture on child elements through traversal techniques

My current dilemma involves working with an object that I've loaded using THREE.ObjectLoader(). This object consists of various elements, resembling a simple box made up of panels and sticks. My goal is to assign different textures to specific child ...