What is the best way to retrieve the value of a v-select field when submitting a form?

I've been struggling to retrieve the value of a select field in my Vue project. Despite trying various methods, some of which I still have references for, I haven't succeeded yet. Here are a couple of links I've used:

Even after all these attempts, I can't seem to capture the selected value. Is there a way to retrieve the selected value in the FormData object? I believe this approach would simplify the process.

Here's how it looks in the template:

<v-form @submit.prevent="update" id="exapi">
            <v-select
              id="select"
              name="select"
              v-bind:items="selectOptions"
              v-model="selectedOption"
              label="Exchange"
              autocomplete
              >
            </v-select>
            <v-text-field
              name="input-api-input"
              label="Enter key"
              hint="Key"
              v-model="password"
              :append-icon="e1 ? 'visibility' : 'visibility_off'"
              :append-icon-cb="() => (e1 = !e1)"
              :type="e1 ? 'password' : 'text'"
              >
            </v-text-field>

            <v-btn
              color="secondary"
              :loading="loading"
              @click.native="loader = 'loading'"
              :disabled="loading"
              type="submit"
              >
              Change API Keys
            </v-btn>
</v-form>

In the script section, I've experimented with multiple methods but haven't had any success:

updateExchangeApi() {
  const form = new FormData(document.getElementById('exapi'));
  const key = form.get('input-api-input');
  const selectValue0 = form.get('select');
  const e = document.getElementById('exchange-select');
  const selectValue1 = e.options[e.selectedIndex].text;

  console.log('in updateExchangeApi()');
  // console.log(exchange);
  console.log(key);
}

Am I missing out on any best practices here? Any advice or assistance would be highly appreciated.

UPDATE: I should mention that I did try setting v-model="selectedOption" with selectedOption in data, but I'm still unable to fetch the value:

data: () => ({
  loader: null,
  LineChart,
  BarChart,
  UserTable,
  selectedOptions: [],
  selectedOption: '',
})

However, when I log selectedOption from my form submit function, I get 'undefined':

console.log(self.selectedOption);

Answer №1

Using a form object in Vue's data function is an alternative approach to FormData.

The form object can house all the properties that will store the values of your form inputs.

You can easily retrieve the form object within your submit function by utilizing this.form.

See the example below for implementation:

<template>
     <v-form @submit.prevent="submit">
      <v-select
       v-model="form.selectedItems"
       :items="items"
       multiple
       label="Select"
       item-value="value.foo"
       item-text="text"
      ></v-select>
     <v-text-field v-model="form.text"></v-text-field>
     <v-btn type="submit">submit</v-btn>
   </v-form>
</template>

<script>
   export default {
    data: function () {
     return {
      items: [
       { text: "Item 1", value: { foo: "item", bar: 2 } },
       { text: "Item 2", value: { foo: "test", bar: 42 } },
       { text: "Item 3", value: { foo: "foobar", bar: 4 } },
      ],
      form: {
        selectedItems: [],
        text: "",
      },
    };
  },
  methods: {
    submit() {
      const formData = this.form;
      // log the form data
      console.log(formData);
      //... handle data 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

Remove duplicate elements from a JSON array

How can I add each item in an array for each duplicate? Transform: [ { "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60", "planning":[ { "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84", "star ...

When performing the operation number.tofixed in Typescript, it will always return a string value instead of a double datatype as expected from parseFloat

let value = 100 value.toFixed(2) -> "100.00" parseFloat(value.toFixed(2)) -> 100 I am encountering an unexpected result with the double type when input is 100.36, but not with 100.00. Framework: loopback4 ...

How to pass event data when clicking on a div using React

I'm curious about how the onClick event flows in React when clicking on a div. In my application, there's a ParentComponent that renders a ChildComponent which generates a div for each item in the props.options array. I have a couple of questio ...

Guide on how to import a CSV file into an Angular project using tensorflow.js

Having trouble uploading a CSV file from the assets folder in my Angular project using tf.data.csv. The code doesn't seem to recognize the file, resulting in an empty object being created. Can we even upload a CSV via tf.data.csv() from the assets? An ...

Refresh numerous HTML <div>'s using data from a JSON object

Looking to automatically update the homepage of my website with the ten most recent "posts" from the server. Here's an example HTML format: <div id="post1"> <p id="link"> </p> </div> <div id="post2"> <p id="li ...

Guide for integrating the shadcn/ui Range Date Picker within a Form

Encountering an issue with using The Range Date Picker within the Form component. Specifically, I am looking to store {from, to} values of the range in an object, however, utilizing an object as a Form field value results in error messages not functioning ...

Generate a string that will be utilized to interpret a JSON response

I can't seem to extract a specific element from a json using a dedicated function. Can someone please assist me with this issue? Here is the fiddle that I have created for reference: http://jsfiddle.net/jonigiuro/N5TTM/2/ CODE: var data = { "res ...

The multi-subrow feature in Material-UI tables does not support simultaneous hovering

I have integrated a table from material-ui into my project, similar to the image shown below: My issue is that when I hover over a specific row in the table, the background color changes to dark. However, some rows may contain sub-rows and I want these su ...

Expanding Drop-Down Feature in CodeIgniter: How to Create Nested Dropdown Menus

I'm working on a dropdown menu that is populated with items using a foreach statement. When an item is selected, I need another dropdown menu to appear where specific items can be specified. First Dropdown - Categories (Completed) When a Category is ...

"Divs are now linked and drag as one cohesive unit instead of

As I was experimenting with making images draggable and resizable, I encountered a small issue. When I attempted to drag two or more images, they would merge into one large draggable object instead of remaining separate. My goal was to make each image drag ...

mdButton causing multidir error

I attempted to integrate <md-button> from angular-material, however, I encountered some difficulties. Specifically, I kept receiving a [$compile:multidir] error. More details about the error can be found in this Error link. If you're interested, ...

Add a class if the particular class is missing from the webpage

Seeking a solution in JS, I am facing a challenge in creating a series of elements with active states, each opening a caption below when clicked. Utilizing .addClass, .removeClass, and .toggleClass in combination, only one element can be active at a time. ...

Unable to display items in controller with AngularJS

I am facing an issue with displaying a slider using ng-repeat in my AngularJS code. The pictures and other elements defined in the controller are not showing up on the page. Here is the JavaScript code snippet: angular.module('starter', []) .co ...

Assign an id attribute in KineticJS once the ajax call is successful

I have implemented KineticJS into my MVC application. To retrieve data from the database, I am utilizing ajax calls to web services in the API controller. One of the APIs returns an id that I want to assign to the current Kinetic.Group id attribute upon s ...

Encountering cross-domain issues while integrating AngularJS in flex (web control), and trying to retrieve templates/json (local files)

To provide some background on my current endeavor, I am utilizing a Flex application to serve as a container for a web app. Within this Flex app resides a web controller that loads a complete Angularjs application. All necessary files are stored locally wi ...

Connect my asp.net grid view to JavaScript using AJAX

I am seeking guidance on how to bind my gridview from JavaScript in an ASP.NET web forms application. My objective is to click a linkbutton within my gridview and have it trigger a modalpopup that displays another gridview. Here are snippets of my code s ...

The issue with using useState on arrays is that it is not functioning properly with React Hooks

const [LatestNews, setLatestNews] = useState([]); useEffect(() => { async function fetchLatestData() { const result = await database.collection('latestnews').get(); result.docs.forEach(doc => ...

Don't forget to retain filled values when navigating with Vue Router

I have a quick and straightforward question that I would appreciate your input on. In my Vue router setup, I have added navigation tabs for "Home" and "Configuration." On the "Configuration" page, I input some data without saving it, then navigate back t ...

Struggling to make dynamically created SVG 'use' elements function properly

SVG offers a unique system with symbol and use where icons can be defined once and reused throughout the SVG using use. However, I am having trouble getting it to work from JavaScript. You can view an example on this JSFiddle link. When programmatically ...

Manipulating and inserting objects into an array using React and Typescript with an undefined type

As I embark on my TypeScript journey in React, I decided to test my knowledge by creating a simple Todo App. Everything seems to be working fine except for one issue! After adding a new task and hovering over it, I received the following error message (tr ...