Published on: 02 Mar, 2021

How to set radio button checked in Vue.js?

Tumblr Digg Google Plus

If you have a group of radio buttons and want to bind and set a radio button to be checked. You can perform a condition against the checked property value of the radio button. Each of the radio buttons needs to be set a unique value. 

Let's say we have two radio buttons that will have a label text 'Yes' and 'No' with a supplied value of 1 represents the Yes value and 2 represents the No value.
See below screenshot of a question with two radio buttons answer.

Let see the following HTML source code for the above screenshot.


<!doctype html>
<html>
	<head>
		<title>bytutorial.com Demo - Set radio button checked</title>
	</head>
	<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
	<body>
		<div id="app">
			<p>Have you learn Vue.js before?</p>
			Yes <input name="learnGroup" type="radio" value="1" :checked="checkedValue == '1'">
			No <input name="learnGroup" type="radio"  value="2" :checked="checkedValue == '2'">
		</div>
	</body>
	
	<script>
		var app = new Vue({
			el: '#app',
			data: {
				checkedValue: ""
			},
			
			mounted(){
				this.checkedValue = "1";
			}
		});
	</script>
</html>

Firstly, you will notice that we create a VueJS model variable that will hold our checked value which either can be 1, 2, or an empty string. If you set the value to an empty string in the 'mounted' method. It will clear the radio button selection. In the above example, we set the value equals 1 which will set the radio button for the 'Yes' answer to be checked.

If you see in the input checked property, we insert a condition that will compare the model value against the value. If it is matched, it will then return a true value which will set the radio button to be checked.

Demo

To see the live demo, you can click the following link.

See the example of setting a default value for a select combo box in action.

Download

To download the demo file. Please click the following URL link.

Download file.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.