Eduardo Reyes
Eduardo Reyes

Reputation: 113

How can I get the value of the value attribute of an option tag with Vue js?

I have a component that renders a select tag. The select tag contains the twelve options for the months, each option has the value attribute, this attribute has a number, from 1 to 12 for each month, so I want to get the value of this value attribute of the option tag tha is selected and then sync this value with a variable of de data property of my component. I'm working with Vue JS.

<select v-model="month" class="form-control form-control-sm">
<option>Selecciona el mes</option>
<option  value="1">Enero</option>
<option  value="2">>Febrero</option>
<option  value="3">>Marzo</option>
<option  value="4">>Abril</option>
<option  value="5">>Mayo</option>
<option  value="6">>Junio</option>
<option  value="7">>Julio</option>
<option  value="8"> >Agosto</option>
<option  value="9">>Septiembre</option>
<option  value="10">>Octubre</option>
<option  value="11">>Noviembre</option>
<option  value="12">>Diciembre</option>
</select> 

Upvotes: 0

Views: 686

Answers (1)

gleam
gleam

Reputation: 870

You can do something like that: https://jsfiddle.net/5k1fc9tj/

But it would be better if you will do it through data, not through html markup: https://jsfiddle.net/5k1fc9tj/1/

<div id="app">
  You select {{ selectedMonthName }}
  <br />
  <select v-model="selectedMonth" class="form-control form-control-sm">
    <option value="null">Selecciona el mes...</option>
    <option v-for="month in monthes" :value="month.id">{{ month.name }}</option>
  </select> 
</div>

new Vue({
  el: "#app",
  data: {
    selectedMonth: null,
    monthes: [
      {id: "1", name: "Enero" },
      {id: "2", name: "Febrero" },
      {id: "3", name: "Marzo" },
      {id: "4", name: "Abril" },
      {id: "5", name: "Mayo" },
      {id: "6", name: "Junio" },
      {id: "7", name: "Julio" },
      {id: "8", name: "Agosto" },
      {id: "9", name: "Septiembre" },
      {id: "10", name: "Octubre" },
      {id: "11", name: "Noviembre" },
      {id: "12", name: "Diciembre" },
    ],
  },
  computed: {
    selectedMonthName() {
        for (let month of this.monthes) {
        if (month.id === this.selectedMonth) {
            return month.name;
        }
      }
      return 'nothing :)'
    },
  },
});

Upvotes: 1

Related Questions