What is the best way to link a select dropdown with an input field in Vue.js?

My goal is to connect a select box with an input field. The select box contains pre-defined options, and when an option is selected, it should appear in the input field. Additionally, if the user types text into the input field, a new dynamic select option should be created if it does not match any of the pre-defined options.

<div class="col-md-2 text-center">          
   <select class="form-control" v-model="selected">
    <option v-for="item in inventory" :value="item" :key="item.id">
      @{{ item.name }}
    </option>
  </select>
  <p>
    @{{ selected.id}}
  </p>            
</div>

<input v-model="inputBind" placeholder="," type="text" class="form-control">

In addition:

 new Vue({
    el:'#app',
     data:{
       inputBind:'',
       inventory: [
          {name: 'MacBook Air', id: 1},
          {name: 'MacBook Pro', id: 2},
          {name: 'Lenovo W530', id: 3},
          {name: 'Acer Aspire One', id: 4}
        ],
        selected: 2
      },
     created: function() {
          this.selected = this.inventory.find(i => i.id === this.selected);
      },

Answer №1

Utilize the same data attribute for the input, refer to this JS Fiddle to ensure the data is shared by both inputs. This method is the simplest. Keep in mind that in order for the select box to choose the correct option, you must input the matching value. It's unclear why you would need it this way, as it may not be very user-friendly.

Javascript

new Vue({
el: '#app',
data: {
    selected: 'item1',
    input: '',
    items: {
      1: {id: 1, val: 'item1'},
        2: {id: 2, val: 'item2'},
        3: {id: 3, val: 'item3'},
    }
  }
});

HTML

<div id="app">

  <select class="form-control" v-model="selected">
    <option v-for="item in items" :value="item.val" :key="item.id">
     {{ item.val }}
    </option>
  </select>

  <p>
    {{ selected }}
  </p>

  <input v-model="selected" placeholder="," type="text" />

</div>

Answer №2

To incorporate the change event, you can use the following code snippet to execute a function after the model value has been updated:

<select class="form-control" v-model="selected" @change="doSomethingWithChangedValue">
    <option v-for="item in inventory" :value="item" :key="item.id">
      @{{ item.name }}
    </option>
</select>

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

Confirmation of successful email delivery displayed through contact form and toast notification

I must be missing something obvious because I can't seem to get this right. Could you lend me a hand? Currently, I am developing a contact form in Vue and Vuetify using EmailJS along with a Toast (iZiToast) notification. My goal is to display the to ...

The integration of Laravel (Homestead) Sanctum is malfunctioning when combined with a standalone Vue application

After running the command php artisan serve my Laravel application successfully resolves on localhost:8000. I have configured Laravel Sanctum as follows: SESSION_DRIVER=cookie SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=localhost:8080 As for m ...

Using the `scrollIntoView()` method to continuously scroll through elements in Puppeteer

My goal is to extract a list of posts while the page is continuously loading. I am using scrollIntoView() for each element within a loop. Currently, my code looks like this temporarily. When the page loads, the result bounces out without any errors. for (l ...

Tips on moving a square along the z axis in three.js

Can anyone provide assistance with translating a square on the z axis in three.js? I would appreciate any examples or guidance on the best approach to achieve this. ...

The audio event continues to trigger even after it has been removed using removeEventListener

In my React component, specifically handling an audio track with an HTML <audio> element, I have implemented the following lifecycle methods: componentDidMount() { const {track} = this.props; this.refs.audio.src = track.getTrackUrl(); _.each(t ...

The complexity of reading code increases when ajax requests are nested

I often prefer to structure my code in a way that one function triggers multiple other functions, like the example below: /** * GET MESSAGES: */ $(function() { $.ajax({ url: '/messages', method: 'GET', dataType: 'j ...

Is there a way to refresh an item in an Express JS router automatically after a set period of time?

Is there a way to automatically update a mongoose schema through a post request after a certain period of time? I have a task that requires changing the boolean value from "livestream: false" to "livestream: true" within an hour or at a specified time. An ...

The database is failing to reflect any changes even after using the db.insert function

I am currently working on implementing a forgot password feature in my express app using the node mailer package. This functionality involves sending a new password to the user's email and then updating the database with the new password. However, I h ...

Create a nested object or dictionary in JavaScript by recursively combining a group of arrays

I'm feeling a bit puzzled trying to figure out a solution for this particular problem. So, I have a series of arrays and the goal is to create a JSON-like object based on them. For example: [a] [a, b] [a, b, c] [a, b, d] [e] [e, f] [e, f, g] shoul ...

What is the best way to instantly update $scope when working with non-angular code?

Working with a non-angular library requires establishing communication between them. <div id="MoipWidget" data-token="{{personaltoken}}" callback-method-success="successCB" callback-method-error="errorCB"></div> Upon page load, a token must b ...

Click events attached to individual items in a v-for loop are triggered multiple times upon clicking

My code includes a @click handler that is bound to individual items within a v-for loop. Ideally, each item in the loop should have its own unique click event, triggering the associated function only once when clicked. However, I am experiencing an issue ...

Retrieving the value of the selected radio button

How do I access the value of a clicked radio button? I am trying to create a custom filter based on the gender selected in my <form>. However, when using the filter and orderBy in my ng-repeat, it is not functioning correctly. You can view an examp ...

Is there a way for me to monitor a prop using the composition api?

Is there a way to trigger a function upon prop update? The parent container structure is as follows: <div> <Maintable :type="typeRef" :country="countryRef" /> </div> And here's the child container code: e ...

Node.js unable to verify RSA-PSS signature due to validation issues

I currently have a JavaScript client and a Node.JS server setup. My goal is to sign a basic text on the client side, send the signature along with the publicKey to the server, and have the server verify the publicKey. Everything seems to work fine on the ...

Adjusting the display location of the icon

I'm working on an AngularJS table and I need to add a text field for filtering/searching. However, the automatically generated icon is not displaying in the right place. Here is my current view: <table> <theader> <tr> < ...

Establishing a connection to a MySQL database in passport.js to deserialize user

Is there a way to handle deserialization of a User in passport.js when connected to a database? It was functioning properly with an array, but encountered issues once linked to the database. What steps can be taken to resolve this problem? Error: Failed ...

Search for styling cues within the text and transform them into distinct elements

I was inspired to develop a unique text editor that utilizes cues within the text, such as :strong:, to set formatting rules. Here is the code snippet I have so far: <?php $document = $_GET["document"]; $user = $_GET["user"]; if ($user != n ...

My Ruby on Rails app seems to be malfunctioning in a major way

Instead of sharing code snippets, I’ve encountered difficulties in getting my jQuery code to work correctly. If you're curious, you can view the issues on Stack Overflow: Why doesn’t this jQuery code work? and This jQuery hide function just does n ...

Attempting to input data into elements that have been generated automatically

Trying to set values to elements with automatically generated id's: This code is functional: <input type="tekst" id="<?php echo $item->getId();?>"> <script> document.getElementById("<?php echo $item->getId();?>").v ...

Can SailsJS be used exclusively for API processes?

Can SailsJS be used solely as an API? After downloading the Sails project, is it possible to exclude the views and focus only on utilizing Sails as an API? ...