Creating an autocomplete select dropdown for United States states in JS/Vue: A step-by-step guide

I am currently working with an array of state objects:

states = [
    {name: "California", abbreviation: "CA"},
    {name: "New York", abbreviation: "NY"},
]

When using browser autocomplete, I have noticed that it functions properly when I set the v-model to only reference the abbreviation field:

<select>
    <option v-model="selectedState" v-for="state in states" :value="state.abbreviation">
       {{ state.name }}
    </option>
</select>

/// selectedState = "NY"

However, my requirement is for the v-model selectedState to be the entire object and due to this, autocomplete does not work as expected:

<select>
    <option v-model="selectedState" v-for="state in states" :value="state.abbreviation">
       {{ state.name }}
    </option>
</select>

/// selectedState = {"name": "New York", "abbreviation": "NY"}

Is there a solution or any alternative method to achieve this functionality?

Answer №1

Utilize a computed property to retrieve the desired object based on the selected value

    computed: {
        selectedCountry() {
            return this.countries.find( item => item.value == this.selected );
        }
    }

Check out this sample code snippet

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

A guide on understanding tab-formatted text in a textarea using JavaScript (Vuejs)

Trying to decipher a text that has been copied into a Word table, the formatting is very confusing. I am looking to extract the rows as objects in an array, with the columns serving as properties of each object. I would like to accomplish this using Vuejs ...

What is your strategy for managing errors when utilizing xui's xhr functionality?

Recently, I've been utilizing the code below to extract data from an external source. <script type="text/javascript"> xui.ready(function() { var url = 'http://www.domain.com/getData.aspx'; x$().xhr(url, ...

Discover the steps for integrating an object into a Ext.grid.Panel using Sencha Ext Js

Currently, I am utilizing Sencha Ext Js 4 and have integrated an Ext.grid.Panel into my project. I am interested in adding another element inside the header, such as a textbox. Is this achievable? {filterable: true, header: 'Unique' /*Here i w ...

Preventing the use of special characters in URLs using JavaScript

I have a treeview where I am dynamically adding nodes and attaching a JavaScript click function to each node. The issue is with the use of the escape function on the url values stored in thisFileNode.Value. Even after using the escape function in my code, ...

Request for a new login using credentials via ajax

We've set up a web application on a LAMP(PHP) system that makes around 40 Ajax calls. Users are tracked using PHPSessions with a 1 hour cookie lifespan (which we want to maintain for quick expiration). ISSUE: If a user is inactive for the full hour an ...

Guide for toggling two mutually exclusive radio buttons in HTML

I am facing an issue with two radio buttons. My goal is to have one radio button checked while the other becomes unchecked when clicked, and vice versa. Unfortunately, the code I have written so far is not achieving this: <input type="radio" ...

Error: Unable to access undefined properties while trying to read 'add' value. Issue identified in the code related to "classlist.add" function

I am currently facing an issue where I receive the error message: Uncaught TypeError: Cannot read properties of undefined (reading 'add') when trying to add a class to a div using a button. After researching on Stack Overflow, I stumbled upon a ...

Can Vite generate a manifest.json file containing customized object content?

Can Vite create a custom manifest.json or other JSON file during the build process that includes paths to the index.js and css files with unique hashes? For instance: { jsScript: 'path/to/script/[name][hash].js', anotherKey: 'myOwnValue&apos ...

How can I properly choose distinct values for an individual attribute from a JavaScript array containing objects?

Let's imagine a scenario with an array of JavaScript objects like this: var data = [ {category : "root", type: "qqqqq", value1: "aaaaa", value2: "zzzzz"}, {category : "root", type: "qqqqq", value1: "aaaaa", value2: "xxxxx"}, {category : " ...

Remove classes from every input, textarea, and select element within a designated div using jQuery

Remove Class from Input, Textarea, and Select Elements in Specific Div Using jQuery Looking to remove a specific class from input, textarea, and select elements within a designated div using jQuery. The HTML structure is as follows: <h4 class="subHea ...

Styling on Material UI Button disappears upon refreshing the page

I've been using the useStyles function to style my login page, and everything looks great except for one issue. After refreshing the page, all styles remain intact except for the button element, which loses its styling. Login.js: import { useEffect, ...

What is the correct way to define the field name in the update() function of Mongoose?

When attempting to update every field contained in the dataToChange object, I encountered a problem where the update() method does not take the key name from the outside. Instead, it looks for a "key" field within the database's object. How can I work ...

Tips for maintaining consistent heights for two div elements in jQuery MobileEnsure that two div elements in jQuery

I am brand new to the jquery mobile framework and seeking your patience as I navigate through it. In my current project, I am required to display data in a tabular format. To achieve this, I have set up a structure with left and right columns: <div dat ...

Retrieve information from a dropdown menu that is dependent on the selected value from another dropdown

   Check out this sample API data - I currently have three dropdown menus set up: From Release To Release Compatibility When a specific from release is selected, all corresponding to releases associated with that specific from release should be displ ...

Is it possible to validate an email domain using node.js? For example, checking if gmail.com is a valid email domain, and ensuring that users do not enter incorrect variations such as egmail.com

I've been working with React.js and Express.js/Node.js, utilizing nodemailer for sending emails. However, I've noticed that a lot of emails are coming in with incorrect domains, such as [email protected], rather than the correct ones like [e ...

Pursue cellular devices

Looking to customize CSS media queries specifically for mobile devices, like so: @media (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 1.5dppx) { /* yo ...

Integrate a feature in React-native MapView that dynamically swaps out markers with different images

Thanks to the insights shared in this informative article, I successfully integrated observations into my MapView. mapMarkers = () => { return this.state.items.map((item) => <Marker key={item.id} coordinate={{ latitude: item.g ...

Utilize and store images based on the individual user's preferences with PlayCanvas

Currently, I am immersed in a PlayCanvas endeavor where I am trying to render specific objects with textures of my choice. The main issue arises when I come across the config.json file in the PlayCanvas build. Within this file, there is a designated path ...

What is the best way to duplicate a Typescript class object while making changes to specific properties?

I have a Typescript cat class: class Kitty { constructor( public name: string, public age: number, public color: string ) {} } const mittens = new Kitty('Mittens', 5, 'gray') Now I want to create a clone of the inst ...

When using firebase.firestore(), the data displayed is completely different and does not match the content of my actual database documents

I am trying to fetch data from firebase firestore using the following code: let db = firebase.firestore(); let locations = db.collection("location"); console.log("locations", locations); However, the logged data is coming back strange and not showing the ...