Adrian kevin
Adrian kevin

Reputation: 45

How do i bind select box with input in vuejs?

I try to bind select box with input so I have a select box with pre defined options and when selected that option will be in the input and when the user types text in the input a dynamic new select option should be made if it is not in the pre defined list else it should match on one of the items.

<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">

and

 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);
      },

Upvotes: 2

Views: 19100

Answers (2)

Holtwick
Holtwick

Reputation: 1967

You can bind to change and which is fired after the model value has been updated like so:

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

Upvotes: 2

Vincent T
Vincent T

Reputation: 3262

Use the the same data attr for the input, check js fiddle that way data is shared by both the inputs. Its is the easiest way. Note that for the select box to select the correct option now you must enter the matching value. Don't know what the reason is you need it this way but its not that user friendly.

Js

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>

Upvotes: 4

Related Questions