1

I looked everywhere to solve this one but I couldn't find any information about it. I have a normal select HTML tags with dynamic options and a form. All I need is to show the latest created category as the selected option by default so I'm passing the options from laravel with orderByDesc and I can see that when I click on the dropdown it shows the latest on top but it never show any value by default which means selected attribute isn't working.

web.php

'categories' => auth()->user() ?
            category::where('user_id', auth()->user()->id)->orderByDesc('created_at')->get()
            : []

frontend

<select
                        name="category_id"
                        id="category_id"
                        class="min-w-max text-sm text-gray-900 bg-transparent border-2 rounded-xl"
                        v-model="productForm.category_id"
                    >
                        <option
                            v-for="category in categories"
                            :key="category.id"
                            :value="category.id"
                            selected
                        >
                            {{ category.name }}
                        </option>
                    </select>

the form

const productForm = useForm("createProduct", {
    category_id: null,
    categName: null,
    title: null,
    price: null,
    type: null,
    currency: null,
    desc: null,
    qty: null,
    thumbnail: null,
});

If there is a better approach to select menus with InertiaJS I would really appreciate your help

Mostafa Said
  • 739
  • 2
  • 6
  • 20
  • Does this answer your question? [How can I set the default value for an HTML – Linus Juhlin Jul 24 '22 at 21:43
  • 1
    You are setting the `selected` attribute on all instances of the ` – Linus Juhlin Jul 24 '22 at 21:44

1 Answers1

1

While using Inertia.js, you can set the default value on the form itself. Since we're using v-model to pass the input value to the form, set the default value on the form itself.

const productForm = useForm("createProduct", {
    category_id: 1,
});

This will set the selected value to '1' by default.

Mostafa Said
  • 739
  • 2
  • 6
  • 20