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

One way to enhance user experience is by passing parameters dynamically from the database when an element is clicked. This allows for the retrieval of

Earlier, I tried to post a question but couldn't get it working due to incorrect code. As the title suggests, my objective is to retrieve data from a database and display it in a div. The idea is that when this data is clicked, it should be passed to ...

Submitting Multi-part forms using JQuery/Ajax and Spring Rest API

Recently, I started exploring JQuery and decided to experiment with asynchronous multipart form uploading. The form includes various data fields along with a file type. On the server side (using Spring), I have set up the code as follows: @RequestMapping ...

What is the best way to trigger my web scraper within an express route?

Within my Nodejs server's root directory, I have implemented a web scraper using needle to handle the HTTP requests for retrieving HTML data. This scraper returns an Array of data upon completion. In addition, there is an index.js file containing expr ...

Looking for a way to streamline data transfer using script setup in Vue 3? Consider utilizing composables to simplify the process

In the scenario where there is a parent component labeled as "1" with two child components named "2" and "3", each of these components containing its own child component, "4" for "2" and "5" for "3", the challenge arises on how to pass state from child c ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

Adding up values of objects in a different array using Vue.js

Recently, I started using VueJs and encountered an object that contains arrays. One of the tasks I need to accomplish is to display the total sum of all amounts in one of the columns of the table. Here is my table structure: < ...

Guide to Increasing Table Index within Nested Loop in Vue.js 3

How can I increment table indices within a nested loop in Vue.js 3? I am currently working with two-level deep arrays using Vue.js, and I need an index that starts at 1 and increases for each item in the top-level array. The desired output is as follows: ...

Need to specify a parameter type for the input tag in HTML

Currently, I am developing a customized focus method for my webpage using the following script: <script type="text/javascript"> function myFunction() { document.getElementById("name").focus(); } </script> I ...

Transforming a JSON structure into a tree model for use with the angular-tree-control component

I need help converting a complex JSON schema into a format compatible with Angular Tree Control. The issue is that the schema does not follow the required treemodel structure for Angular Tree Control, particularly because the children in the schema are not ...

ng-if behaving unexpectedly

This is a demonstration of how I populate the Table and attach checkboxes to a controller: <tr ng-repeat="key in queryResults.userPropNames"> <td><input type="checkbox" data-ng-checked="selectedKeys.indexOf(key) != -1 ...

Encountered an issue when trying to establish a connection to the MySQL database on Openshift using a

I am currently running a Node.js app with Express that is deployed on OpenShift. I have set up databases using the PHPMyAdmin 4.0 cartridge. Although I can establish a connection to the database, anytime I run a query, it throws an ECONNREFUSED error. Whe ...

Numerous HTML documents being uploaded to the server for a multitude of individuals

Currently, I am developing a game on a website where players create new rooms and are assigned specific roles with individual powers. Some players need to wait for input from others, creating a dynamic gameplay experience. Additionally, there are certain ...

Python Selenium error: NoSuchElementException - Unable to find the specified element

Coding Journey: With limited coding knowledge, I've attempted to learn through various resources without much success. Now, I'm taking a different approach by working on a project idea directly. The goal is to create a program that interacts wi ...

What is the best way to check for date equality in Node.js?

I am dealing with this code condition: stopped_at: { $lte: new Date(Date.now() - 86400 * 1000) } The above code successfully retrieves dates that are less than or equal to 24 hours ago. However, I am wondering if there is a simpler solution a ...

Ways to troubleshoot the "TypeError: Cannot read property 'value' of null" issue in a ReactJS function

I keep encountering a TypeError: Cannot read property 'value' of null for this function and I'm struggling to pinpoint the source of the issue. Can someone help me figure out how to resolve this problem? By the way, this code is written in R ...

Show me a list of either only development or production dependencies in npm

When attempting to list only the production dependencies from package.json according to the npm docs, I tried: npm list -depth 0 -prod or npm list -depth 0 -only prod However, npm continues to list both dependencies and devDependencies. Can anyone sugg ...

Utilizing WordPress to dynamically update the footer content on a targeted webpage by modifying the HTML/PHP/JS code

Let me provide some clarity. Details: - Website built on WordPress This website is bilingual with Hebrew and English languages. The issue is with the footer section. I have 4 lines that need to display: - Address: ........ - Phone: ....... - Fax: ...... - ...

Concealing URL parameters in ui-sref (using ui.router)

Here is the HTML code I am working with: <a ui-sref="videoParent.Display.video({videoName:'[[sVid.slug]]', videoId:'[[sVid.videoID]]'})"><p>[[sVid.name]]</p></a> The parameters videoName and videoId are retriev ...

Fixing the mobile display issue with react-responsive-carousel

I am relatively new to ReactJS and I am looking to develop a responsive Carousel. Here is the code snippet that I have currently: To achieve a responsive Carousel for both desktop and mobile devices, I utilized the react-responsive-carousel library. The ...

Revamping reactivity for component props in Vue 3

Within my EditTransaction component, I am calling it in the following manner: <edit-transaction v-if="editableTransaction.id === transaction.id" :key="'transaction'+transaction.id+etcount" :class="{'bg ...