Incorporate fresh data into dropdown options upon selection using Vue3

Can anyone assist me with populating specific input fields on a form using Vue 3? Currently, when a user selects an option from my dropdown menu, all inputs are displayed instead of just the relevant ones.

Below is the select dropdown code:

<select
 v-model="selectedInverter"
 @change="onChange($event)" >
   <option
     v-for="(item, index) in options"
     :value="item.inverter"
     :key="index" >
       {{ item.inverter }}
   </option>
</select>

Here are the available options:

export default {
  name: "ExampleOptions",
  data() {
    return {
      address: "",
      stakeAddress: "",
      selectedInverter: null,
      addressError: "",
      apiKey: null,
      filteredOptions: "",
      options: [
        {
          inverter: "None",
          options: []
        },
        {
          inverter: "Eagle",
          options: [
            {
              name: "Cloud ID",
              value: null,
              description:
                "The Rainforest cloud id used to access your system data",
              type: "text",
              required: true
            },
            {
              name: "User",
              value: null,
              description: "The Rainforest cloud username",
              type: "text",
              required: true
            },
            {
              name: "Password",
              value: null,
              description: "The Rainforest cloud password",
              type: "password",
              required: true
            }
          ]
        },
        {
          inverter: "Efergy",
          options: [
            {
              name: "Token",
              value: null,
              description: "The Efergy token used to access your system data",
              type: "text",
              required: true
            },
            {
              name: "Power",
              value: null,
              description:
                "The Efergy power key, usually 'PWER' or 'PWER.1234' where 1234 is the sid",
              type: "text",
              required: true
            }
          ]
        }
      ]
    };
  },

Check out my example on Codepen: https://codepen.io/pistell/pen/BaJPjgq

Currently, all dropdown examples are visible at once. How can I only show the options related to the selected dropdown item? Also, I am utilizing Tailwind CSS for styling.

Answer №1

If I understood correctly, you can try the following snippet:

new Vue({
  el: "#demo",
  data() {
    return {
      address: "",
      stakeAddress: "",
      selectedInverter: null,
      addressError: "",
      apiKey: null,
      filteredOptions: "",
      // TODO: Create a way to iterate over these values and populate the HTML elements that go along with each of these
      // https://stackoverflow.com/questions/43250578/vue-js-populate-new-selects-when-changing-the-main-one
      options: [
        {
          inverter: "None",
          options: []
        },
        {
          inverter: "Eagle",
          options: [
            {
              name: "Cloud ID",
              value: null,
              description:
                "The Rainforest cloud id used to access your system data",
              type: "text",
              required: true
            },
            {
              name: "User",
              value: null,
              description: "The Rainforest cloud username",
              type: "text",
              required: true
            },
            {
              name: "Password",
              value: null,
              description: "The Rainforest cloud password",
              type: "password",
              required: true
            }
          ]
        },
        {
          inverter: "Efergy",
          options: [
            {
              name: "Token",
              value: null,
              description: "The Efergy token used to access your system data",
              type: "text",
              required: true
            },
            {
              name: "Power",
              value: null,
              description:
                "The Efergy power key, usually 'PWER' or 'PWER.1234' where 1234 is the sid",
              type: "text",
              required: true
            }
          ]
        }
      ]
    };
  },
  computed: {
    computed_items() {
      const selected = this.selectedInverter;
      return this.options.filter((item) =>  item.inverter.includes(selected));
    }
  },
  methods: {
    async registerInverter() {
      this.addressError = this.address.length > 1 ? "" : "Not a valid address";
      if (!this.addressError) {
        await this.validateAddress();
        // Values to send to Firebase
        console.log({
          address: this.address,
          api_key: this.apiKey,
          date_registered: new Date().toUTCString(),
          inverter: this.selectedInverter,
          stake_address: this.stakeAddress
        });
      }
    },
    async validateAddress() {
      // Evaluate the address and check if its valid
      console.log(this.address);
      return this.address;
    },
    onChange(event) {
      this.selectedInverter = event.target.value;
    }
  }
})
...

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

Transferring an image between two <td> cells within the same table

For a project, I'm working on creating a Checkers game. I have the checker board and pieces ready, but I'm struggling with the movement logic. My goal is to enable the image to move or transfer from one td element to another when clicked. A frie ...

The Vuetify v-spacer does not seem to be working as intended

When using the <v-dialog> modal, I am attempting to stick one block to the bottom of the <v-col> block by utilizing the <v-spacer> component, but it does not seem to have any effect. What could be causing this issue? You can view an exam ...

Preventing users from copying and pasting information from my form by implementing javascript restrictions

I'm looking for a solution to prevent users from copying and pasting in my form using JavaScript. I want to restrict the ability to paste or copy any content into the form. Any assistance would be greatly appreciated! ...

Troubleshooting issues with Laravel and Vuejs before deploying on Heroku

Hello there! I recently conducted an experimental project using (laravel-with-vue) and deployed it on Heroku. However, when I open the application, all I see is a blank screen. Upon inspecting the item, I found the following code snippet: <body data-new ...

HtmlWebpackPlugin can cause issues with loading relative path files on websites that are not located in the root directory

I have set up webpack and the HtmlWebpackPlugin to automatically include bundled js and css files in an html template. new HtmlWebpackPlugin({ template: 'client/index.tpl.html', inject: 'body', filename: 'index.html' ...

Comparing the architecture of two JSON objects in JavaScript without taking into account their actual content

One of the tools I rely on for my projects is a Node.js based mock server that helps me specify and mock API responses from the backend. However, it would be beneficial to have a way to ensure both the backend and frontend are in sync with the specified st ...

Angular and JavaScript: Today is Monday and the date is exactly one week old

I am currently working on an Angular application that is connected to a REST API. In order to minimize the number of requests made, I have implemented a method to store all data in the local storage. .factory('$localstorage', ['$window&apos ...

I wish to trigger the function when the button with the ID "add_city" is clicked instead of it being activated upon pressing the Enter key as it currently is

Is it possible to trigger the function by clicking a button with the id "add_city", rather than just pressing Enter? function createCity(stateId, newCity, event) { if(event.keyCode == 13 || $(this).attr('id') === 'add_city') { i ...

Tips for Selecting an Object within an Object in a v-for Loop

One challenge I'm facing is figuring out how to display a list of songs from various artists in alphabetical order. Currently, I've implemented a nested v-for loop to achieve this, but it doesn't seem to work as expected. I have tried using ...

How should a string be properly converted to JSON format?

I am encountering an issue with converting the following string to JSON format const banner = " { "banners": [ { "startDate": "02/26/2021", "endDate": "12/25/2021","content": "Important ...

Encountering a NULL argument in an MVC controller when executing an Ajax post request

I am facing an issue with my ajax post request where I send JSON string data, but it is showing null in my controller. Here is the AJAX Call: var jsonData = JSON.stringify(matrixPresenter); $.post("/matrix/Savematrix?matrixData=" + jsonData , fu ...

Tips for making sure there is a delay in between each axios call in a React

Currently in the process of developing an application that needs to interact with a RestAPI by sending a specific set of inputs. However, the API has a major flaw when it comes to scalability and tends to respond with code 429 if bombarded with too many re ...

What is the relationship between three.js transforms and CSS3 3D-transforms?

I am developing a unique open-source tool for exploring and visualizing the complexities of human anatomy. At the center of this tool is a dynamic 'chessboard' that occupies the majority of the screen. As you drag the board, various CSS3 3D-tran ...

What is the best way to retrieve the axios baseUrl in nuxt?

In my Nuxt.js project, I have incorporated the axios module. The baseUrl for my API is set to 'localhost:4040/api', while my client is functioning on port 3000. However, when retrieving image data from the API, it outputs a relative path to the s ...

Unpacking Reddit's JSON data in a Node environment proves challenging as the Javascript parser seems to have a distaste for

Hey there, I hope everything is going well! I've been working on a project that involves scanning the JSON data from reddit.com/r/pics. My goal is to extract a random image and display it on a webpage. The issue I'm facing is that Reddit's ...

Calculating the mean value of the numbers provided in the input

I'm struggling with calculating the average of numbers entered through a prompt window. I want to display the numbers as I've done so far, but combining them to find the average is proving difficult. Here's the code I have: <html> &l ...

Best practices for sending an object from client to server using Node.js

What is the best way to transfer a large object from client side to my node.js server? The object is currently stored in a variable within my script tags. ...

Cache for AngularJS $http.jsonp requests

I'm struggling with caching a JSONP request and have tested out different approaches without success. I attempted $http.jsonp(url, { cache: true }) and $http({ method: 'JSONP', url: url, cache: true }), but neither worked as expected. As a ...

Save the contents of a file within an HTML table using jQuery

I needed to insert multiple files into the database by uploading and adding each file's content to a table. Once all files were added to the table, I included the table's values along with the file content in form data which was then passed to aj ...

using VueJS, learn how to dynamically apply text to a data variable based on certain props

I'm facing an issue with conditional value assignment to the data variable based on props. The ternary operator is causing errors in my code. Here's a snippet for reference: <template> <div class="absolute left-3 top-1/2"> ...