<option value="">Select an option</option> <option value="option1">Option 1</option> <option value="option2">Option" />

PASSWORD RESET

Your destination for complete Tech news

Vue

How to get the selected text from an option in Vue?

495 0
< 1 min read

In Vue, you can get the selected text from a dropdown menu using the v-model directive and the event.target object. Here’s an example:

<template>
  <div>
    <select v-model="selectedOption" @change="getOptionText">
      <option value="">Select an option</option>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option>
      <option value="option3">Option 3</option>
    </select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedOption: '',
    };
  },
  methods: {
    getOptionText(event) {
      const selectedIndex = event.target.selectedIndex;
      const selectedOptionText = event.target.options[selectedIndex].text;
      console.log(`Selected option text: ${selectedOptionText}`);
    },
  },
};
</script>

In this example, we have a dropdown menu with three options. The v-model directive binds the selectedOption data property to the value of the selected option. The getOptionText method is called when the dropdown menu value changes. The event.target object contains information about the target of the event, which in this case is the select element. We get the selected index using event.target.selectedIndex and then get the selected option text using event.target.options[selectedIndex].text. We then log the selected option text to the console.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.