Search code examples
javascripthtmlvue.jsdomv-model

Vue.js: How to get attributes of an option in Select dropdown box?


If we bind a Select box values like the following Example:

<select v-model="car">
 <option number="one">BMW</option>
 <option number="two">Audi</option>
 <option number="three">Mercedes</option>
</select>

How can I get the value of the number attribute instead of the Name of the car in Vue.js?


Solution

  • You should use value instead of number :

    <select v-model="car">
     <option value="one">BMW</option>
     <option value="two">Audi</option>
     <option value="three">Mercedes</option>
    </select>
    

    selected value will be assigned to car property.

    Example :

    Vue.config.devtools = false;
    Vue.config.productionTip = false;
    
    new Vue({
      el: '#app',
      data() {
        return {
          car: ''
        }
      }
    })
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
    
    
    <div id="app" class="container">
      <select v-model="car">
        <option value="one">BMW</option>
        <option value="two">Audi</option>
        <option value="three">Mercedes</option>
      </select>
      
      {{car}}
    </div>