x-model and select/option default values #4140
Replies: 1 comment 2 replies
-
You don't need the x-init part, it's "just" (I appreciate is not as smooth as but there are technical reasons that you can find at the bottom of this post) <script type="module">
import { Alpine } from "https://unpkg.com/[email protected]/dist/module.esm.js";
Alpine.start();
</script>
<main x-data="{
countries: [
{ id: 'IT', name: 'Italy' },
{ id: 'FR', name: 'France' },
{ id: 'DE', name: 'Germany' },
],
selection: ['IT', 'FR'], // I wan them to be preselected
}">
<h1>Alpine -- Model and Select X</h1>
<pre x-text="JSON.stringify($data, null, 4)"></pre>
<select multiple x-model="selection">
<template x-for="country in countries" :key="country.id">
<option
x-bind:value="country.id"
x-bind:selected="selection.includes(country.id)"
x-text="country.name"
/>
</template>
</select>
</main> Opposite to Vue, Alpine runs directly on the browser and real dom. Directives are processed top to bottom. When alpine starts processing the x-model on the select tag, the tag itself is empty (the inner c-for hasn't run yet) so, despite it setting the value, the browser has no options to mark as selected. when the inner x-for runs, Alpine manipulates the DOM to enter the options. Browser are not smart enough to check if an option is meant to be selected when you inject it at a later stage so you need to manually add the selected property. |
Beta Was this translation helpful? Give feedback.
-
Hi !
I come from Vue and study Tailwind/Alpine/Laravel/Livewire stack.
An observation about select/option model initial value.
With Alpine I do⤵️
Whereas with Vue I can simply do⤵️
The Vue solution is much more natural and elegant. Am I missing something or is select/option initial value really not supported natively by Alpine x-model ? In this last case, is a support considered ?
The situation is ~identical with select1.
Thx,
Beta Was this translation helpful? Give feedback.
All reactions