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

Guide to organizing a one-to-one object map within Angular JS ng-repeat

Is there a way to organize a one-to-one object map in angular.js using filters (or any other technique) while working within an ng-repeat loop? This is what I currently have: obj:{ a:3, c:5, d:1, g:15 } Basically, I want to achieve s ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

Problem with RadioButton click event not triggering

Among my collection of RadioButton elements, there is an onclick event that should trigger. This event, named SecurityCheckedChanged, will display or hide other div containers (populated with RadioButton elements) based on the selected RadioButton. Howeve ...

Tips for adjusting the minimum attribute within an input field with jQuery

In my form, I have an input field with arrows (up and down). Next to it, there are two buttons: + and -. When I click on the input field and then use the arrow, the system retrieves the value from a dropdown list, which works fine. However, when I use the ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...

Tips for creating a mock for a function that yields a JSX Element

I am facing a problem where I have a function that returns a JSX Element. Here is a snippet of the code: myFunction.jsx const myFunction = (props) => { // ... do something with props return <MyElement {...newProps} /> } // MyElement.j ...

Struggling to create an access token with the Slack API

My goal is to retrieve an access token from the Slack API. When I use the code provided below, it generates an authorization URL containing a temporary code in the query string. Once permissions are granted, the process redirects to /slack/oauthcallback. ...

React.js onClick does not display the dropdown

Hello, I have a question regarding my navbar icon functionality. When I click on the icon, it is supposed to open a dropdown menu. However, although the div name changes when clicked, the CSS properties remain the same as the initial class. I am unsure w ...

Tips for sending JSON data from JavaScript to PHP servers

After encoding an array into JSON using JavaScript, I set up my ajaxrequest object like this: var data = JSON.stringify(cVal); function ajaxRequest(url, method, data, asynch, responseHandler){ var request = new XMLHttpRequest(); request.open(meth ...

How can I determine if a URL in react js includes a specific string?

I am working on a project where I need to check if a given URL contains the string youtube using react hooks in React JS. This is what my current code looks like: useEffect(() => { let srcLink = "www.google.com/https://img.youtube.com/vi/h9-qcy3HQn ...

Exploring techniques to maintain search functionality on altered display columns in DataTables.js

How can I ensure that the search functionality works properly on the modified render column in DataTables.js? In the code snippet provided below, my attempts to search data within the render columns are not yielding any results. $('#release-table& ...

Encountering a JSON parse error while utilizing the getJSON function

First time delving into coding with JavaScript and JSON, encountering an error message when using getJSON: parsererror SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data return window.JSON.parse( data ); Below is my code ...

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

Creating a function to manipulate an element on a different webpage

Upon clicking a button on Page1, a function is triggered which then calls another function to generate HTML and append it to a div with the #lista id. The issue here is that #lista belongs to Page2, so I am unsure if there is a syntax similar to ajax where ...

ERROR: An issue occurred while attempting to resolve key-value pairs

Within my function, I am attempting to return a set of key-value pairs upon promise completion, but encountering difficulties. const getCartSummary = async(order) => { return new Promise(async(request, resolve) => { try { cons ...

Matching wildcard paths using Express

Seeking help with routing in Express. I am trying to have both /m/objectID and /m/someslug/ObjectID directed to the same function. My current setup is as follows: app.get("/m/:id", ...); app.get("/m/(.*)/:id", ...); The first route is working properly, b ...

Loading indicator for buttons

Issue with submit button onclick function (onClick="mandatoryNotes()"). It is taking a while to load, so a preloader script was added. The preloader is now working, but the function is not being called. Seeking assistance. Thank you. function mandatoryN ...

What is the best way to reset react-id-swiper every time an event handler is triggered in a React application?

I have incorporated the react-id-swiper module into my React project to create a dynamic image slider. By setting onClick event handlers on buttons with different id attributes, I trigger API calls that update the state and populate the ImageSlider compone ...

How can you calculate the ratio of one property value to another in AngularJS?

In my code, I am using ng-repeat to display data values from an object. <div ng-controller="myctrl"> <ul ng-repeat="number in numbers"> <li><span ng-bind="number.first"></span></li> <li><span ng-bind ...

Clearing input fields after entering information

Is there a way to automatically assign the value from a scanner input to a variable in an input box and clear it for the next input? HTML <ion-view hide-nav-bar="true"> <ion-content class="padding"><br> <label class="item item ...