Tips on resetting v-model after changing select options

In my project, I have implemented a cascading select feature where the options in the second dropdown are dependent on the value selected in the first dropdown. This is achieved by using a computed property based on the first select to populate the options in the second select. While this setup works well for the most part, I am encountering an issue.

The problem arises when I choose an option in the second select (which updates the bound variable value via v-model) and then proceed to change the value in the first select. As a result, the options in the second select are updated accordingly, but visually it appears as though I have no selection in the second dropdown. However, the bound variable retains its previously selected value. I suspect that this occurs because updating the options for the second select does not trigger an input or change event, causing v-model to not respond. Although I could address this with a watcher, I was hoping to find a more elegant solution.

For a coded example, you can check out this link: https://codepen.io/Slotheroo/pen/ajwNKO/

JS/Vue:

new Vue({
  el: '#app',
  data: {
    selectedFruit: null,
    selectedVariety: null,
    fruits: {
      "apples": [
        {
          name: "honeycrisp",
          madeBy: "applebees",
        },
        {
          name: "macintosh",
          madeBy: "the steves",
        },
        {
          name: "gala",
          madeBy: "ac/dc",
        },
        {
          name: "pink lady",
          madeBy: "Alecia Beth Moore",
        },
      ],
      "pears": [
        {
          name: "d'anjou",
          madeBy: "Maya D'Anjoulou",
        },
        {
          name: "bartlett",
          madeBy: "Anton Yelchin",
        }
      ],
    },
  },
  computed: {
    fruitVarieties: function() {
      return this.fruits[this.selectedFruit]
    }
  },
});

HTML:

<div id="app">
  <div>
    <select v-model="selectedFruit">
      <option value=""></option>
      <option v-for="fruitName in Object.keys(fruits)" :value ="fruitName">{{fruitName}}</option>
    </select>
  </div>
  <select v-model="selectedVariety">
      <option value=""></option>
      <option v-for="fruitVariety in fruitVarieties" :value="fruitVariety">{{ fruitVariety.name }}</option>
    </select>
  <div>
  </div>
  <p>Selected variety: {{ selectedVariety }}</p>
</div>

Steps to reproduce:

  1. Select 'apples' from the first select dropdown
  2. Choose 'honeycrisp' from the second select dropdown
  3. Now, pick 'pears' or leave it blank in the first select dropdown

Expected outcome:

The selectedVariety should revert back to null

Actual outcome:

The selectedVariety remains as honeycrisp

Answer №1

To improve the functionality, I suggest implementing an on-change handler on the initial <select> tag in order to reset the selectedVariety whenever a new option is selected...

<select v-model="selectedFruit" @change="selectedVariety = null">

Check out this demonstration on CodePen


An alternative approach could involve setting up a watch on the selectedFruit variable, although Vue framework typically leans towards utilizing event handlers for such scenarios.

Answer №2

When utilizing version 3.0.0, there is a particular feature involving :reset-on-options-change='true'

For example:

<v-select required  :options="filterKaryawan.unit.options" :reset-on-options-change='true' v-model="filterKaryawan.unit.selected" placeholder="placeholder" >
   <template #search="{attributes, events}">
       <input
           class="vs__search"
            v-bind="attributes"
            v-on="events"
            :required="filterKaryawan.unit.selected"
       />
   </template>
</v-select>

Answer №3

The calculated attribute is essentially acting as a listener. Therefore, place the code to reset the value within it.

computed: {
    bookGenres: function() {
      this.selectedGenre = null; 
      return this.books[this.selectedBook]
    }
}

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

AJAX form encountered a bad request error with code 400

JavaScript Issue: function submitForm(){ var data = { name: _("#name").value, email: _("#email").value, message: _("#message").value } var output = JSON.stringify(data); var ajax = new XMLHttpRequest(); ajax.open( "POST", "/src/scripts/pa ...

Issue with Angular failing to identify jQuery after transferring the dependency from package.json to bower.json

Initially, my project included angular, angular-bootstrap, and jquery in the package.json file, with everything being compiled using browserify. // package "dependencies": { "angular": "~1.4.6", "angular-bootstrap": "~0.12.2", "jquery": "~2.1. ...

Encountered a React 16 error: Unexpected TypeError stating that this.state.userInput.map is not a valid

I am working on a simple React app where a user can input text and I want to display each character as a list. Here is the progress I have made so far: App Components import React, { Component } from 'react'; import './App.css ...

Having trouble syncing a controller with AngularJS

Despite numerous attempts, I am still struggling to make a single controller function properly. Lately, I've been working on Angular projects and no matter what I do, my controllers just won't cooperate. In my latest project, everything is withi ...

Encountered a problem while trying to upload a file using node

Hi there! I seem to be facing an issue with the code snippet below. Every time I attempt to upload a file, the browser keeps loading indefinitely. Any thoughts on what might be causing this problem? app.js var formidable = require('formidable') ...

Keeping returning visitors engaged without triggering negative reactions from bots: What's the best approach?

Looking to provide new visitors with an introduction on certain pages of website.com without being repetitive if they have already seen it. For example, if a user lands on website.com/cool-article, the introduction is displayed at the top. However, when t ...

Refreshing the lightbox once new ajax content is loaded

While there are similar questions and answers related to my issue, I have not been able to apply them successfully. As a beginner in this area, any assistance is greatly appreciated. I am currently working with CubePortfolio, which is a jQuery-based, filt ...

Create a new Chart.js visualization using information retrieved from an external API

Seeking to initialize a Chart.js chart with an API, I've come across tutorials that update the data post page rendering. However, I wish to update the chart before the page renders, enabling me to view the initialized chart without any reload. <tem ...

Executing multiple requests simultaneously with varying identifiers following a waiting period

I am looking to send a GET request using the user_id key retrieved from the userData object. This is how the request should be structured: Let's assume we have userData defined as follows: var userData = [ { id: 1, user_id: ...

What could be causing the jQuery Mobile DOM element to return 'undefined' when using .val()?

Currently, I am experimenting with Jquery Mobile and facing an issue where my Form elements are returning 'undefined'. I suspect that the problem lies in the fact that my form may not be created when the onclick() function is triggered by the Mem ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

Encountering a non-constructor error while trying to import packages in React Typescript

I am currently working on a project that utilizes React with Typescript. While attempting to import a package, I encountered an error stating that the package lacks a constructor when I run the file. This issue seems to be prevalent in various packages, a ...

After implementing the ng-repeat directive, the div element vanishes

I've been working on fetching data from a Json API and displaying it on user event. However, I'm facing an issue where the div disappears whenever I apply the ng-repeat property to it. Despite searching through various tutorials and documentation ...

Error: Uncaught TypeError - Unable to assign a value to the 'status' property

Hello everyone, I am currently facing an issue with validating the response from my server using Axios in VueJS. axios.post('/login', { email: this.email, password: this.password }).then(response => { if (response.status == 200) { $ ...

What steps can I take to stop Vetur and TypeScript from displaying duplicate TypeScript warnings in VSCode?

I have a Vue2 project using TypeScript in VSCode with Vetur and TypeScript extensions installed. Whenever there is a TypeScript warning, both the TypeScript and Vetur overlays show duplicate warnings. Example of duplicate warnings Also, the intellisense ...

Initiating change notification when utilizing service communication

So I am facing an issue with two unrelated components where I am attempting to establish communication between them using a service and a BehaviorSubject. Despite successfully exchanging data, calling the service from one component does not trigger change ...

Issues with Node AssertionErrors cause failures to be silent and prevent proper error output

I am facing an issue with a particular method in my code. The code snippet is as follows: console.log('Trouble spot here') assert(false) console.log('Will this show up?') Upon running this code within my application, the followi ...

The switch statement remains unchanged for varying variables

Here is some code that I am working with: updateTable(selectedIndex) { console.log("running updateTable function"); let level = ''; // if (selectedIndex == 1){ // this.setState({level: 'day'}) // th ...

How to use jQuery to target the second or any desired div element with a specific class

I'm having trouble with something seemingly simple Let's say we are looking for a class called .contentdiv, for example. I am trying to target the second or nth occurrence of the .contentdiv class in a document and retrieve the HTML of that spe ...

Updating an embedded object in JavaScript

This is the initial dataset const data = { "field1": { "name": 'Anuv', "marks": { "eng": 43, "hindi": 23 }, "age": 21 }, ...