Generate a dropdown menu with dynamic options populated from an API by adding an input type select element dynamically

Greetings! I am working on designing a decision tree that dynamically generates options based on user selections and API responses. When a user chooses a reason option, the corresponding reasons are fetched from the API and displayed in a select dropdown. If the user selects an option that returns additional data from the API, another select dropdown is created below it with sub-reasons. This dynamic creation of select dropdowns continues as long as the API response is not empty.

<template>
// The first select option does not generate 
           <select v-model="reasonOne" @change="eventOne(reasonOne)">
              <option
                v-for="(reason, key) in reasonsOne"
                :key="key"
                :value="reason.value"
                :selected="reason.item === reasonOne"
                @click="eventOne(reason.item)"
              >
                {{ reason.item }}
              </option>
            </select>

// The div will dynamically generate all select options
         <div v-if="showSav">
            <div id="select-pattern" class="step-two__select-wrapper" />
          </div>
<template/>

<script>
  async eventOne(option) {
    let reasonsReturn = await customerApi.getReturnPattern(
          app,
          this.detailReturn.sku.product.id
        );
        if (!this.reasonsReturn.length) {
          this.showSav = false;
        }
        let selectPattern = document.createElement('select');
        let target = document.getElementById('select-pattern');
        selectPattern.className = 'select-create';
        selectPattern.id = 'create-input';
        target.appendChild(selectPattern);
        for (let item of reasonsReturn) {
          let optionPattern = document.createElement('option');
          optionPattern.value = item.id;
          optionPattern.text = item.name;
          selectPattern.appendChild(optionPattern);
        }
        document
          .getElementById('create-input')
          .addEventListener('change', async function () {
            let reasonData = await customerApi.getReturnPattern(
              app,
              this.value
            );
          });
}
</script>

While I have successfully implemented the initial select dropdown, I am facing difficulties in creating subsequent ones. I believe I need to implement a loop to handle the creation of select dropdowns based on API responses when each option is selected, but I am unsure about how to achieve this while making API calls every time an option is changed.

Answer №1

Creating something dynamically can be achieved most easily using a v-for. While your specific code couldn't be replicated, let me demonstrate the basic structure:

TEMPLATE:

Simply utilize a v-for to iterate over each input you wish to create (generated here upon button click)

<div v-for="item in inputs" :key="item.id">
  <!-- PLACE YOUR SELECTION HERE -->
</div>
<b-button @click="addNewInput()">Add new Input</b-button>

SCRIPT:

You need to do two things within your script. First: Establish your data and create the initial input, then set up a method for your click-event to add a new input every time the button is clicked.

data() {
  return {
    id: 1,
    // Starting with your first input
    inputs: [{
      id: this.id += 1,   //incrementing ID for uniqueness
    }]
  }
},

methods: {
  addNewInput() {
    this.inputs.push({
      id: this.id += 1
    })
  }
}

You can accomplish this structure using either a click-event or a for-loop within your methods, but the overall framework remains consistent!

I hope this explanation proves helpful to you!

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

User retrieval failed following successful passport authentication

After a successful authentication, the user is directed to the "/profile" route, as demonstrated in the code snippet below. app.get( "/auth/google/callback", passport.authenticate("google", { successRedirect: "/profile", failureRedirect: " ...

"Interactive Connect 4 Game in Javascript - Drop the disk into the bottom row of the chosen

Check out this awesome Connect4 game I found: http://codepen.io/anon/pen/lmFJf I have a specific goal in mind for the game. When I click on an empty space in any column, I want it to automatically drop into the lowest available spot in that column, follow ...

Switching between the open and close buttons within a Vue component

Just starting out with Vue and need some guidance on implementing a specific feature. I want an open button (icon) in the navigation bar. Clicking it should change it to a close icon and load a new template within the same page. Clicking the close icon sh ...

Connect a function to create a new document element in order to modify the

I am attempting to intercept document.createElement in order to modify the value of the src property for each assignment. My current approach involves: var original = document.createElement; document.createElement = function (tag) { var element ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...

Safari is encountering an issue with the value provided for the width/height attribute in the <svg> element, as it is not a recognized

When adjusting the size of an SVG based on antd breakpoints, I encountered errors like these. I am passing props to an SVG element: const { lg } = useBreakpoint(); const height= lg ? "8rem" : xs ? "3rem" : "5rem"; const width ...

A guide on updating various states using React Hooks

Creating a background component with the use of Vanta in NextJS, here's the code snippet: import { useEffect, useRef, useState } from "react"; import * as THREE from "three"; import FOG from "vanta/dist/vanta.fog.min"; im ...

NPM: Handling multiple prehooks with the same name

Is it possible to have multiple prehooks with the same name in my package.json file? For example, having two instances of pretest: "scripts": { "start": "react-scripts start", ... "pretest": "eslin ...

Convert a string to HTML using AngularJs

Snippet: <tr ng-repeat="x in orderCsList"> <td class="ctn"><input type="checkbox" ng-model="x.checked"></td> <td class="ctn">{{ x.wdate }}</td> <td class="text-left">{{ x.wid }}</td> <td class="te ...

Automating Indesign with HTML5 and JavaScript through IDML files

I am currently working on automating IDML files. My goal is to display an IDML template in an HTML5 editor. Within the sample.idml file, I have a basic TextFrame containing the text "Hello World." After unzipping the file and navigating to the stories fol ...

Strategies for redirecting a PDF download response from an API (using node/express) to a user interface (built with React)

I have a specific setup where the backend server generates a PDF, and when a certain endpoint is visited, it triggers the download of the PDF. However, due to security restrictions, I cannot access this endpoint directly from the frontend. To overcome this ...

Adjusting canvas height in Storybook - Component does not fit properly due to low canvas height

I had a component that I needed to add to Storybook. It was working fine, but the styling was slightly off. I managed to resolve this by adding inline styling with position: absolute. Here is how it looks now: const Template: any = (args: any): any => ( ...

Passing a JavaScript variable to a URL parameter can be achieved by

Can anyone advise me on passing JavaScript string variables and displaying them in the URL? For instance, let's say the URL is "xyc.com". Upon populating a variable (a), I wish for that variable to appear in the address bar as URL = "xyc.com/?a=". Cur ...

Show the helper text when a TextField is selected in Material UI

I would like the error message to only show up when a user clicks on the TextField. Here's my code: import React, { useState, useEffect } from 'react'; import { TextField, Grid, Button } from '@material-ui/core'; const ReplyToComm ...

Issue with populating labels in c3.js chart when loading dynamic JSON data

Received data from the database can vary in quantity, ranging from 3 to 5 items. Initially, a multi-dimensional array was used to load the data. However, when the number of items changes, such as dropping to 4, 3, 2, or even 1, the bars do not populate acc ...

text box with an immobile header

As the browser window size decreases, the layout changes. However, when scrolling down, the search text box moves up and is no longer visible due to its lack of fixation. How can I make the search text box stay fixed as I scroll down? I tried implementing ...

Using JavaScript to apply styling on images with overlays

I am currently facing an issue with placing an overlay on top of a background image. Despite my efforts, I am unable to get the background color to appear on top of the image. Any helpful suggestions on how to resolve this would be greatly appreciated. M ...

How can you make each <li> in an HTML list have a unique color?

Looking for a way to assign different colors to each <li> element in HTML? <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <ul> Here's how you want them displayed: Item 1 should be red Ite ...

How to add a subtle entrance animation to text (demonstration provided)

Apologies for the brevity, but I could really use some assistance with replicating an effect showcased on this particular website: My understanding is that a "fadeIn" can be achieved using jQuery, however, I am at a loss as to how to implement the 3D effe ...

Text field suddenly loses focus upon entering a single character

In my current code, I have functions that determine whether to display a TextField or a Select component based on a JSON value being Text or Select. However, I am facing an issue where I can only enter one letter into the TextField before losing focus. Sub ...