Using Vue.js to dynamically update select boxes

I am in search of the perfect solution to dynamically update a multi-select box based on each selected option.

Logical Approach

https://i.sstatic.net/Nm2fv.png

In reference to the image above, I aim to modify the options (refreshing the list each time without using ".push()") of select 1,3,4,5 when an option is selected in select 2 and so forth.

The data for select 1, 2, 3, 4, 5 will be retrieved from the backend whenever an option in any select box is chosen. Therefore, there will always be new values to replace the existing ones.

Current Issue

My current code successfully populates other select boxes with data, but sometimes the returned data are not arrays; instead, they are objects that should act as single options, leading to multiple empty selections (as shown in the sample image below).

https://i.sstatic.net/kSPPx.png

Sample Example of Returned Data

data: {id: 54, option_id: 1, cable_id: 1, name: "etsahetahe", description: "sthsthrt", position: "Kabel Udara",…}
    id: 54
    name: "etsahetahe"
    description: "sthsthrt"
    option_id: 1
    created_at: "2020-04-27T08:05:06.000000Z"
    updated_at: "2020-04-27T08:05:06.000000Z"
        option: {id: 1, segment_id: 2, cable_id: 2, type: "Backbone", site_name: "12585444-54741115",…}
            id: 1
            type: "Backbone"
            segment_id: 2
            site_name: "12585444-54741115"
            created_at: "2020-04-14T03:51:47.000000Z"
            updated_at: "2020-04-15T08:03:32.000000Z"
                segment: {id: 2, hthree_id: 1, name: "Segment 2", created_at: "2020-04-14T03:36:50.000000Z",…}
                        hthree: {id: 1, area_id: 1, name: "h3i 1", created_at: "2020-04-14T03:36:23.000000Z",…}
                    hthree_id: 1
                    id: 2
                    name: "Segment 2"
                    created_at: "2020-04-14T03:36:50.000000Z"
                    updated_at: "2020-04-14T03:36:50.000000Z"
message: "Data retrieved successfully."

For example, in the returned data provided, the segment is an object and not an array of data. Hence, this object needs to be treated as a single option in my select box.

Code Implementation

https://jsfiddle.net/robertnicjoo/xc5f2btL/2/

new Vue({
  el: "#app",
  data() {
    return {
      option:{
        zone:'',
        area:'',
        city:'',
        segment:'',
        link:'',
        closure:'',
      },
      zones: [],
      links: [],
      areas: [],
      regions: [],
      segments: [],
      closures: [],
    }
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      this.axios.get("/api/maps")
        .then((res) => {
          this.zones = res.data.data;
          this.links = res.data.links;
          this.areas = res.data.areas;
          this.regions = res.data.regions;
          this.segments = res.data.segments;
          this.closures = res.data.closures;
        })
    },
    zoneChange(val, e) {
      axios.post('/api/admin/maps/valChanger', {
          [val]: e
        })
        .then(res => {

          if (val == 'zone') {
            this.areas = res.data.data.areas;
            this.segments = res.data.data.segments;
            this.links = res.data.data.links;
            let links = res.data.data.links;
            for (let i = 0; i < links.length; i++) {
              this.closures = [...links[i].closures]
            }
            this.regions = res.data.data.cities;
          }
          // Other conditions for different select boxes can be added here
          
        })
        .catch(error => {
          var errors = error.response.data;
          let errorsHtml = '<ol>';
          $.each(errors.errors, function(k, v) {
            errorsHtml += '<li>' + v + '</li>';
          });
          errorsHtml += '</ol>';

          this.$notify.error({
            title: 'Filter Error',
            dangerouslyUseHTMLString: true,
            message: errorsHtml
          });
        });
    },
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
.el-select {
  float: right;
 }
<link href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<div id="app">
  <el-row :gutter="10">
    <el-card shadow="always">
      <el-form ref="option" :model="option" label-width="120">
        <!-- Form elements generating dynamic select boxes based on data -->
      </el-form>
    </el-card>
  </el-row>
</div>

In the zoneChange(val, e) {..} function, I endeavor to reset the default values of all select boxes based on the selected option. However, as mentioned in the issue section, it sometimes results in additional empty options being displayed.

Query

What would be the most effective approach for me to achieve my desired logic? Should I consider utilizing the watch method, or is there a better alternative within my existing method that just requires modification?

Your valuable insights and solutions are highly appreciated.

Answer №1

Issue Resolved

To streamline my options, I transformed the object data into an array using the following code snippet:

const newArray = [ res.data.data.link.segment]
this.segments = newArray;

May this solution benefit others facing a similar challenge.

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

Transmitting Several Pictures at Once Through WhatsApp-WebJS

I have encountered a challenge while attempting to send multiple images in a single WhatsApp message using the WhatsApp-WebJS library. Despite receiving a "success" confirmation without any errors, the images and message fail to appear on WhatsAp ...

Discover the collection of classes in a DOM element using Vue 3's composition API

I'm currently working on checking if a class exists in a DOM element within my component, but I'm facing some difficulties while trying to achieve this using the onMounted hook: Below is a simplified version of my template structure: <templat ...

Obtaining text from a select list using JQuery instead of retrieving the value

How can I retrieve the value from a select list using jQuery, as it seems to be returning the text within the options instead? Below is my simple code snippet: <select id="myselect"> <option selected="selected">All</option> <op ...

Cannot adjust Span content with JQuery

I am currently utilizing Bootstrap and JQuery for my project. HTML <div> <ul> <li><strong> Status : </strong><span id="monitorStatusSpan">1111</span></li> </ul> </div&g ...

Restrict Vue Router access to specific pages only

Once a user has logged in for the first time, they are directed to the CreateProfile page where they can enter their profile information. I want to restrict access to this page so that if the user manually types the URL into their browser (e.g. www.myproje ...

Stripping HTML elements of their identifiers prior to storing them in the database

I have been developing an application that allows users to save their own HTML templates. Users will have access to various HTML components and can create static HTML pages using these components. The content of the page is automatically saved using a Jav ...

The completion order of nested jQuery AJAX requests is often unpredictable

In addressing the issue I previously encountered in my earlier query, it seems possible that I was dealing with something known as the X,Y problem. With this question, I am aiming to delve deeper into the core of the challenge I am facing. To view the code ...

Generating HTML widgets dynamically with jQuery: A step-by-step guide

Looking for a way to display an interactive widget on your page while allowing users to generate multiple instances and interact with them simultaneously? Imagine having a widget like this: <div id="my_widget"> <script type="text/javascript" ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Accessing variables declared within a React Native component from another component

I've created a simple grammar app, which I have simplified and showcased on snacks Overview of the App The app currently retrieves and displays sample sentences based on the selected article and noun genders. Goal My goal is to highlight the chose ...

What is the proper way to incorporate an if statement within a new instance?

After creating a new instance, I am looking to disable the pagination based on the variable enablePagination = false. However, I am unsure of how to set the if condition within that instance. If the condition is true, then it should be operational. var ...

Why does the entire page in Next.JS get updated whenever I switch pages?

Currently, I am utilizing Next.JS to create a single-page application website in React. I have successfully set up routing (https://nextjs.org/docs/routing/dynamic-routes) In addition, I have also configured Layouts (https://nextjs.org/docs/basic-features ...

Using Python3 and Selenium with Firefox, the FirefoxProfile.set_preference() method seems to be disreg

Attempting to configure specific preference values on a selenium 2.53.1 operated Firefox 45.0.1 using Python 3.4, such as deactivating JavaScript: >>> from selenium import webdriver >>> profile = webdriver.FirefoxProfile() >>> p ...

The submission of the form is not functioning properly after loading the page using AJAX

Having trouble submitting my form after loading the page with ajax. Here is the code I am using to load the page: The problem occurs after loading the ajax form as a modalbox. function account_list(url) { $.ajax({ type: 'get', url: url, befor ...

What sets response.setHeader apart from response.writeHead?

When it comes to sending a JSON response from my Nodejs server in my application, I have discovered two different methods. However, I am unsure about the distinctions between them. The first method involves var json = JSON.stringify(result.rows); respons ...

Steps for moving data from a JavaScript variable to a Python file within a Django project

I have created a unique recipe generator website that displays each ingredient as an image within a div. When the div is clicked, it changes color. My goal is to compile the ids of all selected divs into one array when the submit button is clicked. I have ...

Nodejs and mysql integrated login system using express

I have created a node.js Express login system with MySQL. Registration and login services are working fine, but the logout functionality is not. Additionally, I want to restrict access to certain pages only to admin users. Here is the file structure: ...

Unpacking Objects in JavaScript and TypeScript: The Power of Destructuring

I have a variable called props. The type includes VariantTheme, VariantSize, VariantGradient, and React.DOMAttributes<HTMLOrSVGElement> Now I need to create another variable, let's name it htmlProps. I want to transfer the values from props to ...

How come I am unable to attach outerHTML to an element using javascript?

I am facing an issue where I am trying to move an element from one part of the page to another using JavaScript. I attempted to use the outerHTML property and the appendChild method to achieve this, but I keep encountering an error message stating that Arg ...

Leveraging Javascript to modify HTML elements generated by a CMS

Our small business decided to partner with Web.com for a year-long contract to create and manage a website with unlimited changes. However, we have encountered limitations with their content management system and lack of technical expertise from their staf ...