How do I ensure that in Vue.js, the select element always has the first option selected even when other options are dynamically shown or hidden?

In my Vue app, I have a select element that dynamically shows or hides options based on the user's previous selections. For example:

<select id='animal' v-model='values.animal.selected'>
    <option value='cat' v-if='legs == 4'>Cat</option>
    <option value='dog' v-if='legs == 4'>Dog</option>
    <option value='bird' v-if='legs == 2 && wings == 2'>Bird</option>
    <option value='snake' v-if='!legs'>Snake</option>
</select>

While this setup successfully displays and hides options based on changing criteria, the selected option sometimes remains hidden even when it should switch to an available option. Is it feasible to automatically update the selected value of the select element when the options change, such as setting it to the first visible option?

Answer №1

To keep track of when the filter value changes and update the selected value based on the first matching value, you can use the following code:

Give this code a try:

<template>
  <div id="app">
    <p>
      Filter Options
    </p>
    <input type="number" v-model="amountLegs"/>
    <br>
    <select id="animal" v-model="selectedAnimal">
      <option
        v-for="(animal, index) in filteredArray"
        :key="index"
        :value="animal.val"
      >
        {{ animal.label }}
      </option>
    </select>
    <br>
    <p>Selected Value: {{ selectedAnimal }}</p>
  </div>
</template>

<script>

export default {
  name: 'app',
  data() {
    return {
      amountLegs: 0,
      selectedAnimal: 'snake',
      animals: [
        {
          val: 'cat',
          label: 'Cat',
          legs: 4
        },
        {
          val: 'dog',
          label: 'Dog',
          legs: 4
        },
        {
          val: 'bird',
          label: 'Bird',
          legs: 2
        },
        {
          val: 'snake',
          label: 'Snake',
          legs: 0,
        },
      ],
    };
  },
  computed: {
    filteredArray() {
      return this.animals.filter(x => x.legs === this.amountLegs);
    },
  },
  methods: {
    onChangeAmountLegs() {
      const selectedAnimal = this.animals.find(x => x.val === this.selectedAnimal);
      const legs = this.amountLegs;
      if (selectedAnimal) {
        if (selectedAnimal.legs !== legs) {
          const animal = this.animals.find(x => x.legs === legs);
          this.selectedAnimal = animal ? animal.val : null;
        }
      } else {
        const animal = this.animals.find(x => x.legs === legs);
        this.selectedAnimal = animal ? animal.val : null;
      }
    },
  },
  watch: {
    amountLegs(val) {
      if (val) {
        this.amountLegs = typeof val === 'string' ? parseInt(val) : val;
        this.onChangeAmountLegs();
      }
    }
  }
};
</script>

Answer №2

Apologies for my limited English skills, but I'll do my best to respond to your query. 1. The v-if directive will destroy and render elements based on a condition. It's advisable to keep track of any changes in the condition. 2. It seems like you want the select value to be bound to the rendered option value when the option is destroyed. To achieve this, familiarize yourself with HTML. Click here for more information

Utilize Vue watchers to monitor the condition. When the condition changes, compare the select value with the values in the rendered options. If it's False, revert the select value to the first option value. 3. Setting values in data and using lists shouldn't be too complicated.

Below is the code snippet:

const app = new Vue({
  el: '#app',
  data: {
    legs: 4,
    wings: 2,
    selected: 'cat',
    optionValueList:['cat','dog','bird','snake']
  },
  watch:{
    legs(newVal){
      if(newVal==4){
        this.selected = this.optionValueList[0]
      }else if(newVal==2 && this.wings==2){
        this.selected = this.optionValueList[2]
      } else if(newVal==0){
        this.selected = this.optionValueList[3]
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select id='animal' v-model='selected'>
      <option :value='optionValueList[0]' v-if='legs == 4' >Cat</option>
      <option :value='optionValueList[1]' v-if='legs == 4' >Dog</option>
      <option :value='optionValueList[2]' v-if='legs == 2 && wings == 2'>Bird</option>
      <option :value='optionValueList[3]' v-if='legs==0'>Snake</option>
  </select>
  {{selected}}
  <input type="number" v-model="legs"></input>
</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

Learn how to successfully place a draggable object into a sortable container while ensuring that the dropped item is a personalized helper element rather than the original object

The jQuery draggable/sortable demo showcases the process of dropping a clone of the draggable item (both draggable and sortable elements share the same structure). However, I am interested in dropping a different DOM structure. For example, when dragging a ...

Caution: A non-boolean attribute received a value of `false`. What is the correct way to provide a boolean value?

I'm encountering an issue with the code below: react-dom.development.js:67 Warning: Received false for a non-boolean attribute high. If you want to write it to the DOM, pass a string instead: high="false" or high={value.toString()}. Despi ...

I need to inform users that this application is not accessible on devices with small screens

Showing this app on a small device is not supported, such as when the device width falls between 320px and 480px. ...

Do developers only need type definitions for npm packages on their local machines?

It is my understanding that type definition modules for npm packages offer developers intellisense, eliminating the need to guess parameter types when using library methods. These modules have proven to be extremely valuable in my typescript project, esp ...

Finding documents in MongoDB where the size of an array exceeds 1

Looking to retrieve documents with an array size greater than 1 in my MongoDB collection Here is a snapshot of my collection: { "_id" : ObjectId("5eaaeedd00101108e1123452"), "type" : ["admin","teacher" ...

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

Examining REST API functionality through the use of a Console, requiring an integer list as a parameter

Currently, I am in the process of testing a REST API to perform an action that requires a list of integers. I am uncertain about how to correctly handle the parameters required for this test. In my request payload, I have included the following: idAttac ...

What does getsession.insert in the Ace Editor return?

Seeking clarification on the return values of the addMarker and insert functions in ace editor's edit session. The official documentation lacks detail, leaving me uncertain. Refer to the edit session API for more information. I've encountered i ...

At times, MomentJS may miscalculate and add an incorrect number of hours

My goal is to add a specific amount of hours to a 24-hour time, but I'm encountering an issue with the time 00:00. The code I've written works correctly for all times except midnight. For example, if I have 01:30 and add 1 hour, it gives me 02:3 ...

The Art of Checkbox Design

Seeking help in replacing the default check mark on a checkbox with an image. Here is the code snippet I am currently using: <html> <head> <style> .bl { background:-webkit-gradient(linear, left top, left bottom, color-stop(0, #175899), c ...

Having trouble utilizing props with Vue axios? Running into an undefined error? Unsure how to properly use props with axios?

https://i.stack.imgur.com/QfCDG.png There seems to be an issue with my saveComment() function in CommentList.vue. It can't find the comments' post_id and causes this error: CommentList.vue?6c27:107 Uncaught TypeError: Cannot read properties of u ...

Execute protractor to open chrome in incognito mode and disable web security for cross-origin resource sharing

Our application performs well in production with CORS enabled. I am working on a project that is not CORS-enabled locally. Is there a way to disable web security for protractor? Can I modify the selenium instance by adding arguments? We are interested in ...

image rollovers for responsive pictures utilizing the picture element and srcset

Trying to find a way to implement an image rollover effect on the picture element within a responsive website. The big question is, can we apply an image rollover to the scrset attribute in the picture tag? An example of an img tag with a JavaScript roll ...

What causes the selected option to be hidden in React?

I created a basic form demo using react material, featuring only one select field. I followed this link to set up the select options: https://material-ui.com/demos/selects/ With the help of the API, I managed to display the label at the top (by using shri ...

Does JavaScript automatically round large numbers?

I have a simple array: myArray = [{"egn":79090114464},{"egn":92122244001},{"egn":10005870397643185154},{"egn":10000330397652279629},{"egn":10000330397652279660},] However, when I append the values from thi ...

"Capturing the essence of your online presence: The

I recently completed a website for my Students Organization, which includes a special page dedicated to recognizing the individuals who helped organize our activities. Each member is represented with a photo on this page, sourced from their Facebook profil ...

Unable to retrieve real-time data from Firestore using getStaticPaths in Next.js

While fetching data from Firebase Firestore using getStaticProps is successful, I encounter a 404 page when attempting to implement the logic for retrieving details of individual items with getStaticPaths. The current state of my [id].js code appears as fo ...

Looking to enclose a search query in JavaScript using quotes, and then remove the quotes on the Python backend

Let's start with my code snippet. This is the HTML section: <form action= "/" onSubmit= "return validate(this);" method= "post"> <!--irrelevant from this point--> Below is the Javascript portion, located later in the file: <scri ...

How to Revalidate a Next.js Dynamic Route Manually Using an API Route?

In my application built with Next.js, I have a dynamic page that displays resources at the route /resource/[id]. When a user edits a resource, such as #5, I want to refresh the cached page at /resource/5. I've created an API route in my /pages direct ...

TypeScript: creating an interface property that relies on the value of another

Is it feasible to have an interface property that relies on another? For instance, consider the following: const object = { foo: 'hello', bar: { hello: '123', }, } I wish to ensure that the key in bar corresponds to the value of f ...