Implementing a dynamic dropdown feature that appears when a button is clicked, allowing users to select

When I click the button, I am dynamically adding HTML select options.

<div id="app">
    <div>
        <button class="button btn-primary" @click="addRow">Add row</button>
        <button @click="showValues">
            Show values
        </button>
    </div>
    <div v-for="row in rows" :id=row.id>
        <button-counter></button-counter>
    </div>
</div>
<script>

    Vue.component('button-counter', {
        props: ['value'],
        template: '<select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select>'
    })
    var app = new Vue({
        el: "#app",
        data: {
            rows: [],
            values: {},
            count: 0,
            selected: ''
        },
        methods: {
            addRow: function () {
                var txtCount = ++this.count;
                id = 'ddl_' + txtCount;
                this.rows.push({ title: "first", description: "ddl1", id });

            },
            showValues() {
                console.log(this.values)
            }

        }
    });
</script>

I have implemented a component to generate HTML select elements dynamically. Each time the 'Add row' button is clicked, a new dropdown is added. I am currently facing an issue where I need to retrieve the values of these dropdowns when the 'Show values' button is clicked.

Answer №1

To access the value, you can add a ref to all components and retrieve the value of the v-model using the $ref. However, in order for this to work, you must also add the v-model to the select component. I have implemented this functionality in your code in a plunker, and it is functioning correctly. For further clarification, please visit the following codepen link:

codepen - https://codepen.io/anon/pen/Qoeybv

Answer №2

Upon observation, I noticed that there is only one "Show values button click" event, while multiple select HTML elements may exist. It is essential to determine which specific element you wish to retrieve. If you aim to fetch all elements, it can be achieved using this.$children as an array of objects. Please refer to the linked resource for more details. As a newcomer to vue.js, I would like to highlight that my approach may not represent the best practice or solution. Each select element has an additional event attached to it, and the showValues() function displays the last select element.

[1]: https://codepen.io/iganchev87/pen/xBvOMJ

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

Tips for capturing the current terminal content upon keypress detection?

After successfully installing the terminal on a test page, I am looking to highlight matching parentheses within it. This is similar to what is done in this example: I have a working solution in place and now need to integrate it with the terminal. ...

What is the best way to call an API within a loop using Node.js?

How can I efficiently make API calls based on page numbers in a loop? I am using the request() function for API calling, but when debugging my code, the response block is not reached and I do not get a response. Can someone please provide guidance on how ...

Encoding and decoding a two-way stream in NodeJS

I am looking to encapsulate a socket within another object that has the following features: - transforms output, such as converting strings into Base64 format - transforms input, such as converting Base64 back into strings (Please note: while my specif ...

Python Flask login screen not showing error message

Currently, I'm in the process of developing a login screen that incorporates Bootstrap and utilizes jQuery keyframes shaking effect. The backend functionality is managed by Flask. However, I seem to be encountering an issue where the error message "Wr ...

Vue unable to load material icons

The icons npm package "material-icons" version "^0.3.1" has been successfully installed. "material-icons": "^0.3.1" The icons have been imported as shown below. <style lang="sass"> $material-icons-font-path: '~material-icons/iconfont/'; ...

Steps to resolve the days.map error:

My map function is, days.map((val)=>val) Upon consoling the days prop, I receive the following output: [Array(7)] 0: (7) ['', '', '', 'Wednesday', '', '', 'Saturday'] length: ...

Instructions for automating the clicking of a Vue/Vuetify card using Selenium with Python

Currently, I am utilizing selenium version 4.0.0 for my project. I encountered a challenge while attempting to click on a Vuetify card element serving as a button. However, I kept encountering errors such as element not interactable: [object HTMLDivElemen ...

Is it possible to return true to asp.net OnClientClick following an Ajax request? Alternatively, is there another method that can be used?

I am currently implementing an Ajax call to verify if a user is logged in. If the user is not logged in, I want to display a login dialog; otherwise, I need OnClientClick to return true so that the form can be submitted. I am considering using a global var ...

Enhance the speed of my Tumblr page by using JavaScript for personalized styling tweaks

-- Hey there! Dear Reader, if navigating Tumblr isn't your cup of tea, let me know and I'll provide more detailed instructions! I recently ran into some glitches on my Tumblr page while using the default theme 'Optica'. Whenever I tri ...

What is the most efficient way to refresh a React component when a global variable is updated?

I've built a React component called GameData that displays details of a soccer game when it is clicked on in a table. The information in the table is updated by another component, which changes a global variable that GameData relies on to show data. S ...

Adapting Classes in Javascript Based on Screen Width: A Step-by-Step Guide

I'm dealing with two separate menus - one for mobile version and one for PC version. However, the mobile menu seems to be overlapping/blocking the PC menu. How can I resolve this issue? I've attempted various solutions such as removing the mobil ...

Without specifying an element, the Vue3 Composition API PerfectScrollbar Plugin cannot be initialized

I'm currently facing an issue while developing a Vue3 Perfect Scrollbar plugin. The problem arises when I try to initialize the object, resulting in the following error: Error: no element is specified to initialize PerfectScrollbar The code for the ...

Dynamic resizing in NextJs does not trigger a re-render

My goal is to dynamically pass the width value to a component's styles. Everything works fine on initial load, but when I resize the window, the component fails to re-render even though the hook is functioning as intended. I came across some informat ...

Strange black backdrop in dialog component

Today I came across a rather peculiar issue and was wondering if anyone else had experienced it and found a solution. The problem is pretty straightforward - when I load up my Vue component with a dialog element from the Element-UI library, the background ...

VueJS implementation of the Navbar Toggler Bootstrap that closes on click outside using a directive

Is there a way to close the Bootstrap-VueJS toggle navbar easily when clicking outside? I have attempted various directive codes, experimented with the vue-click-outside plugin, and tried different examples but haven't had any success. It appears tha ...

transmitting an array from JavaScript to PHP

Struggling with passing an array from JavaScript to PHP for a school assignment. I'm still learning and can't seem to figure out what's missing. Any help would be greatly appreciated. This is the code I've tried: if(bets.length > ...

Generating intricate JSON structures with JavaScript programming instructions

In the world of JSON, I am still a novice. I need to use JavaScript to construct the JSON structure below, but I'm struggling with adding the second element ("12101") and populating the people in the JSON Structure. Below is the code I tried, however, ...

What is the best way to manage sessions in angularjs using javascript?

Only at two specific instances in the application should the login prompt be displayed: When trying to access a page that requires login while not logged in, such as my profile page. When attempting an action that necessitates ...

Steps for Creating an Animation Tool based on the Prototype:

One question that recently came up was: What is the best approach to tackling this issue? Developing a tool that enables designers to customize animations. To make this process easier, it is essential to create an AnimationSequence using JavaScript that ca ...

the script is run only one time

I have developed a unique web component and incorporated it in two distinct sections like this. <div class="sub_container"> <label>Users in Debt</label> <input placeholder="Search by user name" class="input_style ...