Setting the selected option of a select form element dynamically in Vue 3

Is there a way to dynamically set the selected option in Vue 3 when the data value doesn't match any available option value?

Situation:

If Florida (FL) is the stored state value and the country changes from United States (US) to Canada (CA), the State's option value becomes blank. Rather than having it as blank, I want the placeholder item to be shown as the 'selected' option when there is no match.

<template>
    <div>
        <label v-if="data.country === 'US'">
            State
            <select v-model="data.state">
                <option value="" disabled>state</option>
                <option
                    v-for="(state, i) in states"
                    :value="state['code']"
                    :key="i"
                    >{{ state['name'] }}</option
                >
            </select>
        </label>
        <label v-if="data.country === 'CA'">
            Province
            <select v-model="data.state">
                <option value="" disabled>province</option>
                <option
                    v-for="(province, i) in provinces"
                    :value="province['code']"
                    :key="i"
                    >{{ province['name'] }}</option
                >
            </select>
        </label>
    </div>

    <label>
        Country
        <select v-model="data.country">
            <option value="" disabled>country</option>
            <option
                v-for="(country, i) in countries"
                :value="country['code']"
                :key="i"
                >{{ country['name'] }}</option
            >
        </select>
    </label>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import data from '...'
import states from '...'
import provinces from '...'
import countries from '...'

export default defineComponent({
    setup() {
        ...
        return { data, states, provinces, countries }
    },
})
</script>

Answer №1

To set a placeholder value for the option elements, you can assign an empty string to their value attributes:

<option value="" disabled>city</option>
<option value="" disabled>town</option>

Implement a watcher on data.region to update data.city with an empty string whenever the region changes:

import { defineComponent, watch } from 'vue'

export default defineComponent({
  setup() {
    //...
    watch(() => data.region, () => data.city = '')
  },
})

Check out this demo.

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

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...

Tips for extracting a value from a mongodb aggregate operation

I am attempting to retrieve a value from a MongoDB aggregate in order to display it on an EJS page using the totalAmount variable. The result I am currently receiving is [{"totalAmount":42}] and my goal is to extract only the number, in this case, 42. My ...

What is the method for retrieving this data using Javascript?

I received this JSON-encoded data: { "error": { "msg":"Concurrent verifications to the same number are not allowed", "code":10 } } and I tried to access the 'msg' value using JavaScript as follows: $("#buttonPhoneSubmit ...

Image swaps with timer for button

I am working on a project where I have a page with 5 image buttons arranged horizontally. The objective is to have the images on each button change sequentially every 3 seconds in a continuous loop. Here is my code: $(document).ready(function (){ Beg ...

The Javascript navigate method has detected an incorrect language being used

Currently, I am facing a challenge while developing a React JS website related to the navigator issue. Even though my default browser is Chrome and English is set as the language preference, when I check navigator.language it displays "he-IL" instead of En ...

AngularJS fails to prioritize the following element

Here is my HTML code: <div ng-app="app"> <form> <div class="form-group"> <label >Username</label> <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/> ...

Ways to verify the value of a v-model object

Hey there, I'm a newcomer to Vue. Currently, I am working with Vue version 2.6.10 and element-ui version 2.12.0. Below is the response data from my API: API RESULT [ { name: 'Test', age: 18, cash: null, }, ...

Using ReactJS to create different behavior for checkboxes and rows in tables with Material-UI

I am looking to customize the functionality of checkboxes and table rows. Currently, clicking on a row also clicks the checkbox, and vice versa. What I would like to achieve is for clicking on a row to trigger a dialogue box, and for clicking on the chec ...

How can I transfer an array of objects obtained from an ajax call to an observable array?

One of my functions involves making an ajax call and receiving data in the callback. It looks something like this: function fetchData(callback) { //perform ajax if(callback) { callback(data.data); } } If I use the function like this: fetc ...

Sending a blob through AJAX to a different domain using CORS

Could someone please explain why my current request is being blocked by the SO policy restriction? Javascript Code: var blob = new Blob([req.response], {type: "application/octet-stream"}); req = new XMLHttpRequest(); req.open("POST", ws_path(other_contex ...

Issue with pushing inner list<object> in Knockout version 3.2.0

Currently, I am working with knockout.js on an ASP application. The issue I am facing involves a list of objects returned by the controller action to the view, where the objects in the list point to another list of objects. My struggle lies in adding new o ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

The Else clause is executing twice in the jQuery code

https://jsfiddle.net/mpcbLgtt/2/ Creating a function that adds card names to an array named deck and their IDs to another array called cardIds when a div with the class "card" is clicked. The cards available are: <div class='card' id=' ...

Ensure that the width does not decrease

Edited: included fiddle and code snippets I am facing an issue with the width of columns in my layout. The width of the columns is dynamically calculated based on the content they hold. However, when I filter the results using a search input for a specifi ...

How can serverless platforms handle binary data such as PDF files?

I am currently experiencing an issue that involves uploading a PDF file in Vue.js to a serverless Node.js application, resulting in broken file content. This problem occurs due to the serverless platform incorrectly parsing binary data types. How can I e ...

Showing information in Vue.js using v-for loops

I'm currently working on a basic shopping cart system using Laravel and Vue.js. I've been able to add items to the basket and retrieve them successfully up to a certain point, but I'm facing challenges when it comes to displaying these items ...

What methods can I use to ensure the headline remains fixed like the table headers?

I am currently working on creating sticky table headers. Below is an example showcasing my progress and what I am aiming to accomplish. Below is the script I discovered from another source. function makeTableHeadersSticky(tableId) { var thArr = $(tableId ...

Tips for preventing redirection in Vue 3 composition API with asynchronous requests

I have successfully configured a submission form to send data to my email and add it to a Google sheet using the method described in this GitHub link. The process worked seamlessly for both purposes. However, I am facing an issue where upon submitting the ...

Determine the duration/length of an audio file that has been uploaded to a React application

I am working on a React web application built with create-react-app that allows users to upload songs using react-hook-forms. The uploaded songs are then sent to my Node/Express server via axios. I want to implement a feature that calculates the length of ...

data retrieval not refreshing sorting post construction

My challenge involves fetching data from MongoDB with sorting. While it works perfectly on the development server, it fails to update the data after being built and hosted. import Review from "@/models/review"; import connectdb from "@/util/ ...