Resetting a chosen option in a dropdown menu following the selection of an item in a different dropdown using vue-treeselect

I'm currently working on a feature that involves auto-selecting provinces in Thailand. The functionality I am trying to achieve is when Province A is selected from the province dropdown, the district dropdown should automatically update to display values corresponding to Province A. Similarly, selecting Province B should reflect districts in Province B in the district dropdown, although the UI may still show districts from Province A.

Despite referring to treeselect documentation and experimenting with different approaches for several days, I have unfortunately been unable to find a solution :-(

This is how the current UI appears

<treeselect 
    id="province-selected"
    v-model="state.provinceSelected" 
    :options="provinceArr" 
    placeholder="กรุณาเลือกจังหวัด" 
    noResultsText="ไม่พบข้อมูล"
    data-test="province-input"
    :class="{ errorselect: v$.provinceSelected.$errors.length }"
    :normalizer="normalizerProvince"
    @select="getDistrict"
    zIndex="20000"
    :clearable="false"
    :allowClearingDisabled="true"
/>

Answer №1

The VueTreeselect documentation officially mentions that the select event is triggered after selecting an option, independent of value updates. It is recommended to use the input event instead of select, as it is emitted after value changes according to the documentation. This ensures you receive the updated value for the initial selection.

Working Fiddle

Vue.component('treeselect', VueTreeselect.Treeselect)
new Vue({
    el: '#app',
    data: {
        provinceArr: [
            { id: 1, label: 'Province 1', districtArr: [
                { id: 10, label: 'District 01' },
                { id: 11, label: 'District 02' },
                { id: 12, label: 'District 03' },
                { id: 13, label: 'District 04' },
            ]},
            ... (additional data arrays and objects here) ...
        ],
        districtArr: [],
        state: {
            provinceSelected: null,
            districtSelected: null,
        },
    },
    methods: {
        getDistrict: function(node, instanceId) {
            console.log(this.state.provinceSelected, node, instanceId);
            // Populating districts logic
            this.districtArr = this.provinceArr.find(item => item.id === this.state.provinceSelected).districtArr;
        },
        onDistrictSelected: function(node, instanceId) {
            console.log(this.state.districtSelected)
        }
    }
})
<!-- include Vue 2.x -->
<script src="https://cdn.jsdelivr.net/npm/vue@^2"></script>
<!-- include vue-treeselect & its styles. you can change the version tag to better suit your needs. -->
<script src="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.umd.min.js"></script>
<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.min.css">
<div id="app">
    <div>
        <p>Province</p>
        <treeselect 
            id="province-selected"
            v-model="state.provinceSelected" 
            :options="provinceArr" 
            placeholder="Select Province" 
            noResultsText="No Data Found"
            data-test="province-input"
            @input="getDistrict"
            zIndex="20000"
            :clearable="false"
            :allowClearingDisabled="true"
        />
    </div>
    <div>
        <p>District</p>
        <treeselect 
            id="district-selected"
            v-model="state.districtSelected" 
            :options="districtArr" 
            placeholder="Select District" 
            noResultsText="No Data Found"
            data-test="district-input"
            @input="onDistrictSelected"
            zIndex="20000"
            :clearable="false"
            :allowClearingDisabled="true"
        />
    </div>
</div>

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

Embed Vue applications within the container of the main Vue application

My goal is to establish a foundational Vue application that offers essential features such as signing in, navigating with a sidebar, and the flexibility to interchange navbar items. I envision creating separate Vue applications for each navbar item. Main ...

Can a custom javascript object be exported in various formats similar to the Date object?

Consider the following scenario where I have a custom object: function MyObject(a, b){ this.prop = a; this.name = b; this.doSomething = function(){ return "something"; } } var a = new MyObject(4, 'name'); I am looking fo ...

Using a shortcode as a variable in WordPress can enhance the functionality and customization

I have a button shortcode set up on my website that I want to use consistently across all of my posts. My goal is to be able to update the button's details centrally so that any changes made will be reflected in every instance without having to go thr ...

Creating controller functions for rendering a form and handling the form data

When developing a web application using Express.js, it is common to have separate controller functions for rendering forms and processing form data. For instance, if we want to import car data from the client side, we might implement the following approach ...

Can you change req.params in express?

Let me start by setting the stage: I am working on a RESTful API Server with routes dedicated to user management; for example PUT .../users/:id/profile As part of our authentication process, we need to verify the user's identity and crosscheck the i ...

Navigate through an overflowing element in react/next

I have a component with a fixed width and overflow-x-auto. I want to hide the scroll bar and replace it with arrow buttons for scrolling left and right. How can I add this functionality to my component? Here is the code for my component: <div className ...

What is the best way to use Vue to remove elements from the screen once they have been deleted?

I recently started learning Vue and I'm working on a to-do list with checkboxes that allow me to mark items as complete. The functionality of the application is fully operational. When I check a checkbox, the item is added to the completedItems array ...

Issue with Laravel Pusher integration and Vue.js not functioning correctly

Recently, I started using Laravel Pusher with Vue.js and followed this tutorial to create a chat application. Unfortunately, the chat functionality is not working correctly as users are unable to receive messages from each other. image description can be ...

Exploring Object Arrays with Underscore.js

Here is an array of objects that I am working with: var items = [ { id: 1, name: "Item 1", categories: [ { id: 1, name: "Item 1 - Category 1" }, { ...

Error message encountered in Express.js when trying to apply the ejs function: "View is not a constructor"

I am attempting to execute certain tasks before the original app.get function is called. After referring to this page, I applied their method which worked for the most part, except when using a rendering engine. The code snippet below demonstrates what I ...

"Exploring the Power of Logarithmic Slider with Vue and Quasar

I'm currently working on a project utilizing Vue 2 and Quasar 1, where I am attempting to develop a logarithmic slider. Initially, I managed to create a basic example using a native input slider in this code pen: https://codepen.io/tonycarpenter/pen/Z ...

Set YouTube Playlist to start from a random index when embedded

I've been trying to figure out how to set my embedded playlist to start with a random video. Here's what I attempted: <iframe src="https://www.youtube.com/embed/videoseries?list=PLPmj00V6sF0s0k3Homcg1jkP0mLjddPgJ&index=<?php print(ran ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...

Innovative approach for setting up ES6 Grunt configuration

I'm currently setting up Grunt to utilize ES6, aiming to transpile each component's JS file into its own designated folder. Here is my current directory structure: Components └──footer │ └──js │ └──footer.jsx └ ...

When attempting to access API>19 on my Android device, I encountered an error in my Interface to Java that stated: "TypeError: Android.method is not a function."

Having my minimum API set to 16, everything seems to be working fine. However, debugging has become quite a challenge. I've read that after API 19, the Chrome debugger can be used. But when it comes to interfacing with Java code, I encounter the error ...

Building a Vue application with customized authentication for the Google Calendar API in JavaScript

Struggling with understanding the migration from GAPI to GIS in Vue? Google has provided a helpful document on this topic: https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#server-side-web-apps Attempting to implement code from the ...

Accessing elements within a ReactJS map structure using the material-ui Selectable List component is not supported

I'm facing a dilemma. Unfortunately, my proficiency in English writing is not up to par... ※Please bear with me as it might be hard to follow. I'm trying to choose the ListItem component, but for some reason, I can't select the ListIt ...

Tips on utilizing useStyle with ReactJS Material UI?

Is there a way to utilize a custom CSS file in the useStyle function of Material UI? I have created a separate useStyle file and would like to incorporate its styles. Can someone explain how this can be accomplished? input[type="checkbox"], inp ...

Tips for maintaining the state of a page submitted via Turbolinks using Rails 5 and jQuery

My current challenge involves toggling the visibility of a section when a specific element is clicked. Initially, I was able to achieve this functionality successfully. However, complications arose as my application revolves around a todo list where tasks ...

Submitting a form with dynamic columns and rows can be achieved by carefully designing the form to

Below is the form structure: <table id="participants" class="table table-bordered table-hover table-responsive text-center"> <form action="unique-controller.php" method="post" id="uniqueForm" enctype="multipart/form-data"> <input type="hidd ...