How to get the selected option on change with Vue.js and JavaScript?

Spread the love

Sometimes, we want to get the selected option on change with Vue.js and JavaScript.

In this article, we’ll look at how to get the selected option on change with Vue.js and JavaScript.

How to get the selected option on change with Vue.js and JavaScript?

To get the selected option on change with Vue.js and JavaScript, we listen to the change event.

For instance, we write

<select
  name="leaveType"
  @change="onChange($event)"
  class="form-control"
  v-model="key"
>
  <option value="1">Annual Leave/ Off-Day</option>
  <option value="2">On Demand Leave</option>
</select>

<script>
  const vm = new Vue({
    data: {
      key: "",
    },
    methods: {
      onChange(event) {
        console.log(event.target.value);
      },
    },
  });
</script>

to add the @change directive and set it to call onChange with the change $event object.

Then we get the selected option’s value attribute value with event.target.value.

Conclusion

To get the selected option on change with Vue.js and JavaScript, we listen to the change event.

Leave a Reply

Your email address will not be published.