How to get selected value using on change in VueJs
In this article, you will learn about how to get a selected value using on change in VueJS.
In VueJS, you can get a selected value. To do so you need to use v-on:change directives. This is provided by VueJs and you can use it instead of using v-model. Another way of declaring this directive is to write @change. This will also do the same. Let’s see an example of getting a selected value by using v-on:change :
HTML :We will link vue in HTML with a script tag from CDN. Here, in our case, we will take some students name into select tag. See the below example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Vue Basic</title>
</head>
<body>
<div id="student">
<select v-on:change="changeItem($event)">
<option>Select Stuedent Name</option>
<option value="Deven">Deven</option>
<option value="Alex">Alex</option>
<option value="Smith">Smith</option>
<option value="Rathore">Rathore</option>
</select>
<h1 class="output">{{selected}}</h1>
</div>
<script src="<https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js>"></script>
<script src="app.js"></script>
</body>
</html>
Here , we added student name into select and option tag and added v-on:change into select tag. In the next section we will implement VueJs code to make it work.
Note: You can use @change instead of v-on:change. Both are applicable.
JavaScript:
var app = new Vue({
el: '#student',
data: {
selected: "selected",
},
methods: {
changeItem: function changeItem(event) {
this.selected = event.target.value;
}
}
});
Here, In this section, we have implemented the functionality to make things work. If everything works perfectly then if we select an item it will show the output below in heading 1. Let’s see the output below:
Output:
Here, you can see that the moment we have selected an item from the selected option it was showed that particular value in the output below. This is how you can get selected value using on change in VueJs.