VueJS Get Selected Option Text & Value

avatar
Published: Dec 14, 2022 - Updated: Dec 30, 2022

Hello Artisans, today I'll show you how to get selected option value and text both in a VueJS application. We often used to iterate the arrays of object which we take from response which is come from an API. And for value we'll use the ID of that object and in a text we use the name/title. But Sometimes we need the title to be stored in a variable so that later we can use. And that's about my today's tutorial is so that we can easily take the value and text from a selected option.

Note: Tested on VueJS 2.6.14

Getting Value & Text from a Selected Option

We'll use an onChange() method which will fire when we change/select a option. Let's look at the below source code. 

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>VueJs - Get Selected Option Text & Value - shouts.dev </title>
</head>
<body>
	<div id="app">
		<select name="category_id" @change="onChange($event.target)" v-model="selected_option_value">
			 <option value="">--- Select Stack ---</option>
			 <option value="1">PHP</option>
			 <option value="2">Laravel</option>
			 <option value="3">Vue JS</option>
			 <option value="4">React JS</option>
  		</select>
	</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script>
    var app = new Vue({
      el: '#app',
      data : {
      	selected_option_text : '',
      	selected_option_value : ''
      },
      methods: {
          onChange(e) {
          	this.selected_option_text = e.options[e.options.selectedIndex].text ;
            console.log(this.selected_option_value);
            console.log(this.selected_option_text);
          }
      }
    })
    
</script>
</body>
</html>

It'll produce the below output if we change/select a option.

Selected Value and Text

That's it for today. I hope you've enjoyed this tutorial. If you found any difficulties o questions, catch me in comment sections. Thanks for reading. 🙂

 

Comments

No comments yet…