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

What could be causing this JavaScript if statement to malfunction?

I found myself with some free time and decided to create a basic API using JavaScript. What I thought would be simple turned into a frustrating mistake. Oddly enough, my if/else statement isn't working correctly - it only executes the code within the ...

Error: The specified JSON path for Ajax request could not be

Although my expertise lies in C++, I must confess that my knowledge about web development is quite limited. Therefore, please bear in mind that my question requires a simple answer. Recently, I stumbled upon a fascinating C++ library for creating a web se ...

Utilize Vue.js to selectively display or manipulate objects with a

I am currently working on a Vue.js component page that receives data from my backend. The page consists of three different filters/states that users can choose from: Unlabeled, Completed, and Skipped. Unlablled Completed Skipped My approach involves usin ...

What steps are involved in setting up a point distribution system in AngularJS?

My objective is to develop a point allocation system within AngularJS. I have successfully created a basic directive that introduces DOM elements, including a span displaying "0" points and buttons for incrementing and decrementing. The total number of poi ...

Can you please elaborate on the concept of type coercion in JavaScript?

I've come across information stating that when comparing an object with a number, type-coercion occurs. ToPrimitive is called on the object which then invokes valueOf and, if necessary, toString. However, I'm struggling to understand how this pro ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Using raphaeljs and freetransform in conjunction with clip-path

Currently, I am utilizing Raphael along with Elberts FreeTransform Plugin. You can view my progress so far by visiting MyWork The issue arises when I attempt to translate or rotate the set of rectangles within my clip path. Once rotated or translated, it ...

Show a dynamic modal with a widget displayed inside

I am facing an issue with my Angular.js website that is filled with a multitude of widgets. Each widget consists of a template.html file paired with a controller.js file to form an angular module. These widgets are utilized on a dashboard where users have ...

The final version of the React App is devoid of any content, displaying only a blank page

As a beginner in learning React, I must apologize for any basic issues I may encounter. I recently created a shoe store App (following this helpful tutorial on React Router v6) Everything seems to be working perfectly in the development build of my app. ...

Efficiently managing classes with css modules and extractCSS in Nuxt 2

When using Nuxt 2 with CSS modules, I encountered an issue where multiple components resulted in multiple CSS files having the same class. Hello.vue <template> <div :class="$style.title">Hello, World</div> <div :class=&q ...

Error Message: SCRIPT5 - Permission Denied When Trying to Open PDF with Javascript

Despite searching through multiple posts on SO, I have yet to find a solution to my issue. We operate a web form within our LAN that utilizes Javascript's OPEN function to open PDF files. Up until recently, everything was working smoothly. However, ...

Capturing Screenshots with Ionic Framework

I am currently working on an Ionic application that utilizes geolocation via the Google API. However, I am facing a challenge with implementing a feature where a button in the upper right corner should take a screenshot and trigger a popover with options t ...

Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below: // Function to add a new row $(function(){ ...

Bidirectional communication between two AngularJS scopes or controllers utilizing a service

I am facing numerous situations where I require clicks or other interactions to trigger actions in a different area of the webpage (one-way communication). Now, I have encountered a need for bidirectional communication, where changes made in element A can ...

How should one go about creating an npm package out of a vuejs component and testing it locally?

Initially, I created a vuejs project as a test container using vue-cli. Next, I developed an npm package named "vue-npm-example" from a Vuejs component in my local environment and then imported it into the aforementioned testing project. Within the packag ...

What is the best way to set the v-model property to an object that is constantly changing

I'm in the process of creating a dynamic form that allows users to add additional fields by simply clicking on a button labeled "adicionar condição." The concept is similar to what can be seen in the screenshot below: https://i.stack.imgur.com/Mpmr6 ...

Create a custom route variable in Node.js with Express framework

Is there a way to achieve this particular task using express.js? In my express.js application, I have set up a route like so: app.get('/hello', (req, res) => { // Code goes here }); This setup is functional, but I am curious if it is poss ...

Transforming an Ext.data.TreeStore data structure into a JSON format

How can I convert an Ext.data.TreeStore to a string for saving to Local Storage? I tried using Ext.encode() but it's giving me a circular structure error. Has anyone encountered this issue and found a workaround? ...

Tips for implementing personalized command buttons in Kendo Grid with AJAX request utilizing JavaScript

I am struggling with implementing custom command buttons in a Kendo grid that makes an AJAX call using JavaScript to call a web API post action with dynamic parameters (start, stop, restart) behind button clicks. datasource dataSource = new ken ...

JavaScript - If you change the properties of an object within an array, does it automatically set the array as needing an update?

If we were to imagine a scenario where there is an array containing 3 objects, and then I decide to access the second object by its index in order to modify one or more of its properties, what would happen? Would this modification mark the entire array a ...