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

NickCourage's avatar

How do I give an <option> element a selected attribute in VueJS?

<select class="form-control" v-bind:class="{ 'is-invalid' : errors.category_id }" v-model="product.category_id">
    <option v-for="category in categories" :selected="category.id ? true : false" :value="category.id">{{ category.name }}</option>
</select>

I've tried :selected="product.category_id == category.id ? true : false " and have done alot of searching but can't find anything to answer what I thought would be a simple problem

0 likes
6 replies
Nakov's avatar

You are missing the value on the option ie :value="category.id" + you are comparing the ID to nothing, so what you are essentially doing is selecting all, in which case the first one will be selected, so you need:

:selected="category.id === categoryId"

Having categoryId in your data object, and pre-selected.

Ready more here: https://stackoverflow.com/a/43839491/1457270

piljac1's avatar

May I ask why you want to do such thing? Because it doesn't seem like a Vue'ish way to manipulate things.

piljac1's avatar

That's why I asked what I asked. But I think what he wants the "selected" attribute to output in the actual DOM, which is not the v-model behavior.

ardiaja's avatar

Hi, i am sorry if it's too late, because i just had this problem too and right now i found the solution myself, so i just gonna put this comment to remind myself in the future, because i can't find any solution in the internet. i am using VUE 3 btw. you just need to put v-bind:value="" in the select component :

<select class="form-control" v-bind:class="{ 'is-invalid' : errors.category_id }" v-model="product.category_id" v-bind:value="product.category_id">
    <option v-for="category in categories" :value="category.id">
		{{ category.name }}
	</option>
</select>

Please or to participate in this conversation.