Amplify2234's avatar

Amplify2234 liked a comment+100 XP

2mos ago

Alpine.js multi-select not working when using x-model with :selected

This is a common issue when using Alpine.js (and other frameworks like Vue/React) with elements: you should not use both x-model and :selected (or selected) on the <option> elements in a multi-select. This causes conflicting two-way data bindings.

In Alpine.js, x-model is the only thing you need.
Alpine manages the selected values automatically. By manually binding :selected, you’re overriding/competing with x-model (and likely causing DOM patching issues on updates).


How to fix it:

Remove the :selected binding from the option element.
Just use x-model on the select. Here is your corrected code:

<select
    x-model="standard.test_methods_ids"
    class="form-control form-control-sm select2-test-methods"
    :data-uid="standard._uid"
    data-placeholder="Select Test Methods"
    multiple
    required
>
    <template x-for="method in testMethods" :key="method.id">
        <option
            :value="method.id"
            x-text="method.name"
        ></option>
    </template>
</select>

That’s it—no :selected on the <option>.

Alpine will handle binding the array (standard.test_methods_ids) to the selected options for you. When you initialize test_methods_ids (e.g. in your form object), any values present will be reflected as selected in the multi-select.


Summary:

  • Let Alpine manage selected options via x-model on <select> (with multiple attribute).
  • Do not use selected or :selected on <option> when using x-model.

References:

Let me know if you need more help!