Unlocking the Power of Select Options in Vue.js

I am currently learning how to use Vue.js. Below is an example of the Javascript code I have written:

new Vue({
    el: '#app',
    data: {
        classes: []
    },
    created: function () {
        var vm = this
        // Fetch API
        fetch(xxx.json)
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            vm.classes = data.classes;
        })
    }
});

This program fetches a JSON file first. Here is an example of the JSON format:

{
  "classes": [
    {
      "name": "A",
      "students": [
        {
          "name": "Eric",
          "fruit": [
            "apple",
            "banana",
            "orange"
          ]
        },
        {
          "name": "Eickson",
          "fruit": [
            "banana",
            "orange"
          ]
        }
      ]
    },
    {
      "name": "B",
      "students": [
        {
          "name": "Ethan",
          "fruit": [
            "banana",
            "apple"
          ]
        }
      ]
    }
  ]
}

The JSON data is then placed into the data. The goal is to allow users to select items in each class and use HTML to display each class and student.

Imgur

The HTML code looks like this:

<div class="row">
        <div class="col-3" v-for="class in classes">
            Class name: {{ class.name}}</br>
            <div class="form-group row" v-for="student in cless.students">
                <label class="col-form-label col-sm-2">{{ student.name }}</label>
                <div class="col-sm-10">
                    <select class="form-control" :name="class.name+'-'+student.name">
                        <option></option>
                        <option v-for="fruit in class.fruit">{{fruit}}</option>
                    </select>
                </div>
            </div>
        </div>  
    </div>
    <button type="submit" " class="btn btn-primary">Submit</button>

I want to use the submit button to retrieve all selected options. I tried using a method within the function, with the button having @click="submitFunc(), but I'm unsure how to proceed.

If you can provide guidance on how to implement this, it would be greatly appreciated. Thank you!

Answer №1

To accomplish this quickly, there are a few techniques you can apply.

One method involves fetching the selected item from the select element by creating a new function and directly accessing the option.

Begin by adding a function called submitFunc in the method options of your component. Inside this function, target the select element.

new Vue({
//...
  methods: {
     submitFunc: function(){
          let select = this.$el.querySelector('#mySelect'); //include an id for convenience
          let selectedOption = select.options[select.selectedIndex];

          console.log(selectedOption); //this will display the element, enabling you to retrieve its value.
          //carry out any additional tasks here
     }

  } 
})

Another approach, suggested by @Kokodoko, is to make use of Vue's two-way data binding feature. Define a selectedItem property in the data options, link it with the select element using the v-model attribute, and access it within the submitFunc function.

new Vue({
    el: '#app',
    data: {
        classes: [],
        selectedItem: null //this will represent your chosen option
    },
    methods:{
        submitFunc: function(){
            const selectedItem = this.selectedItem;

            //work with the selectedItem as necessary
        }
    }
});

Add the following code to your template:

<select v-model="selectedItem">
   <option></option>
   <option v-for="fruit in class.fruit">{{fruit}}</option>
</select>

<button v-on:click="submitFunc">Submit</butto</answer1>
<exanswer1><div class="answer accepted" i="55862913" l="4.0" c="1556253457" m="1556266212" a="QWJhbmEgQ2xhcmE=" ai="7325182">
<p>There are a couple immediate ways.</p>

<p>First, you can take the selected item from the select element by simple adding a method and taking the option natively.</p>

<p>Create a method <code>submitFunc in your component's method options, in that method, query the select element.

new Vue({
//...
  methods: {
     submitFunc: function(){
          let select = this.$el.querySelector('#mySelect'); //add an id for ease
          let selectedOption = select.options[select.selectedIndex];

          console.log(selectedOption); //will output the element, you can get the value at this point.
          //do something else
     }

  } 
})

Secondly, thanks to @Kokodoko, you can use the Vue's two-way data binding by declaring a selectedItem property in the data options, attaching it in the v-model attribute of the select element, and then accessing it via submitFunc method.

new Vue({
    el: '#app',
    data: {
        classes: [],
        selectedItem: null //this will be your selected option
    },
    methods:{
        submitFunc: function(){
            const selectedItem = this.selectedItem;

            //do something with selectedItem
        }
    }
});

In the template

<select v-model="selectedItem">
   <option></option>
   <option v-for="fruit in class.fruit">{{fruit}}</option>
</select>

<button v-on:click="submitFunc">Submit</button>

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

Adding a "Learn More" hyperlink in a JavaScript loop

To implement a read more link in JavaScript, I utilize the following function: <script type="text/javascript"> function toggleContent(v) { var vbox = document.getElementById('vbox'); vbox.style ...

When utilizing the yo angular-fullstack:endpoint, the message endpoint fails to produce the message.socket.js

Hey there, I've encountered an issue where the yo angular-fullstack endpoint shopPacket is not generating the shopPacket.socket.js file. I attempted to update the yo angular full stack generator, but unfortunately, the problem persists. yo angular-f ...

What is the best way to create a continuous loop of images on a never-ending

Many discussions cover similar topics, but I have not yet found a solution to my specific question. Currently, I am working on creating a model for a website and I am interested in incorporating an infinite rotating gallery with a limited number of images ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...

Tips for providing information for AJAX requests in a Vue.js-CLI application

I successfully have a Vue.js CLI project up and running. It's able to retrieve data through AJAX from localhost on port 8080 using Apache as the server. After I build the project and transfer it to a directory served by Apache, everything works smooth ...

collaborating with numerous JavaScripts

I am currently working on a project that involves several JavaScript functionalities such as an image viewer, carousel, and toggles. Now, I need to implement a pop-up form, but when I add the JavaScript for the pop-up, the entire page stops working. I wou ...

Difficulty encountered when trying to customize a polymer element that has been expanded (paper-slider)

I've been customizing the Polymer paper-slider element to handle an enumerated list and cycle through these values in the slider instead of just showing numeric values. However, I'm struggling with getting the styles to align properly. When you r ...

The installation of npm was unsuccessful due to an unresolved dependency tree

After purchasing the premium dashboard theme from Creative Tim's site, I encountered a problem while trying to work on it. Despite my efforts to install the packages by running npm install, I kept receiving the following error: npm ERR! code ERESOLVE ...

What is the best way to create a fully clickable navbar item for the Bootstrap dropdown feature?

I'm struggling to make a button in a navbar fully clickable for the dropdown to open. Even when I try adding margin instead of padding, it only makes things worse. Can someone help me figure out what mistake I'm making here? Essentially, my goal ...

Apply a style to the div element that contains a TextInput component

As a beginner in the world of React and Material UI, I am currently working with Material UI version "1.0.0-beta.17", React 15.6.2, styled-components 2.0.0, and styled-components-breakpoint 1.0.1. Within a div element, I have two TextInput fields. const ...

The Bcrypt hashed password does not match the password hash stored in Mongodb

When I use bcrypt.hash to encrypt a password, the hash generated is normal. However, when I save this hashed password in MongoDB using Mongoose, it appears to be different from the original hash. For example: Password hash: $2b$10$bUY/7mrZd3rp1S7NwaZko.S ...

Generate a graph showcasing the frequency of character occurrences within a specific column of a .csv file

I'm currently working on creating a graph using d3.js What I need to accomplish is reading the some_column column in a .csv file and counting the occurrences of | to plot them accordingly on the y-axis. The line should be plotted based on the number ...

Remove any JSON objects in JavaScript or AngularJS that match another JSON object

JSON A ['711','722','733','744'] JSON B [{pid: 711, name: 'hello'},{pid: 733, name: 'world'}, {pid: 713, name: 'hello'},{pid: 744, name: 'hellosdaf'}] I am attempting to remo ...

Unable to change data in table TD using AJAX and PHP received JSON array

I am currently facing an issue with a PHP-AJAX script that is responsible for deleting financial rows from a table. The PHP script is functioning correctly and successfully deleting the rows. However, the problem arises within the success function of the A ...

Executing file upload in parent component with Angular 2

Is there a way to initiate a file upload from the parent component of the router? Specifically, I need to execute two functions located in the parent component - openFileSelect and uploadSelectedFile to manage the <input type="file"> element. This i ...

Tips for conducting key down event testing on a material ui MenuList element utilizing react-testing-library

Looking to test the key down event on my MenuList component. Component: import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import * as React from 'react'; export default fu ...

Using $route to obtain URL parameters

I am faced with the challenge of passing the last parameter from the following URL to a $http.get request in my Angular application. http://myurl.dev/users/32 However, I am struggling to figure out how to pass the 32 as the id. Here is what I have tried ...

Is it necessary to include a promise in the test when utilizing Chai as Promised?

Documentation provided by Chai as Promised indicates the following: Note: when using promise assertions, either return the promise or notify(done) must be used. Examples from the site demonstrate this concept: return doSomethingAsync().should.eventua ...

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

Enhancing user interfaces with jQuery by updating DOM elements

Can anyone help me figure out how to update a webpage so it functions as a report that multiple people can contribute to? I'm using forms to collect data and want it to instantly display under the correct category headings. Currently, I'm using j ...