Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hjortur17's avatar

Checkbox checked

Hi, how can I check a checkbox if a value from an array is the same as an id? I have a edit feature for a booking and it's loop through all services available and then I made a computed prop to see what services was chosen in the first place when the booking was made.

How can I check if any of the id's from already chosen services matches id's from all the services?

Here are my for loop (looping trough all the services available):

<div v-for="service in services" v-if="service.carSize === data.carSize && service.visible">
	<input type="checkbox" :value="service.id">
</div>

This is what I have been trying to see if it's was chosen or not:

:checked="checkedService === service.id" 
this on the input

And here is my method to collect all of the checked services:

checkedService: function () {
	let choosenServices = this.data.services;
	let filtered = _.filter(this.services, (v) => _.includes(choosenServices.map(a => a.id), v.id));

	return filtered.map(function (elem) {
		return elem.id;
	});
}

this returns: [4, 7]
0 likes
4 replies
bugsysha's avatar

https://vuejs.org/v2/guide/forms.html#Checkbox

You should power your UI by the data provided to Vue.

Key points to take away from the link above is following:

<input type="checkbox" id="jack" value="Jack" v-model="checkedNames"> // all inputs point to same property by v-model directive
new Vue({
  el: '...',
  data: {
    checkedNames: [] // this is an array that will collect all values from all checked inputs
  }
})

If you want to have something selected, then just push to checkedNames array and it will be checked.

hjortur17's avatar

@bugsysha - I did add the v-model to my checkboxes, but when I want to push all the already chosen services I get this error:

This is how I'm trying to push to the array:

choosenServices: function () {
	let checkedServices = this.data.services;
	let filtered = _.filter(this.services, (v) => _.includes(checkedServices.map(a => a.id), v.id));

	return filtered.map(function (elem) {
		return this.checkedNames.push(elem.id); // here
	});
}
bugsysha's avatar

How do you get the list of services? Via API or how?

hjortur17's avatar

@bugsysha - Yes, via API call

getServices: function () {
			axios.get('/api/get/services')
			.then(response => {
				this.services = response.data;
			});
		}

Please or to participate in this conversation.