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

butifarra's avatar

Select2 problem with Livewire inside an array of n elements

Hi to all. I have spent an entire week on this, so I give up. I wanted to use a Select2 select with search, wired to a Livewire variable, since the template I use has them, to search for products. After two days I found out that I need the wire:ignore directive so it doesn't lose its appearance when reloading. And after four days more I found out that I need JavaScript (which I don't know) to make it work with wire:model without losing the connection. I made it work with this code, which assigns the variable in the Livewire component manually.

@script
    <script>
        $(document).ready(function() {
            $('#productos').select2();
            $('#productos').on('change', function(e) {
                Livewire.dispatch('producto-elegido', {
                    id: $('#productos').select2("val")
                });
            });
        });
    </script>
@endscript

All set there. The question is that I am making a form to add Invoices, and the invoices can have n lines. So, I need to let the user add lines, and each line must have a new Select2 tied to a new item in the $lines[] array. And I can't put that code of above per each line, first, because it would be too cumbersome, and two, I don't know how to programatically create and point to id names. Because each line should have a Select2 with a new id: something like , being index the iteration variable of the lines array. So, what do you suggest? Discard completely Select2? Another totally different approach? I searched to no avail another select with search for Livewire, no luck. Thank you very much in advance.

0 likes
1 reply
samuelaustinudhedhe's avatar

Hello,

You should use dynamic IDs for each Select2 instance and a reusable JavaScript function to initialize Select2 on each dynamically created dropdown. I'll also show you how to wire everything together using Livewire events.

Livewire Component (InvoiceLines.php) First, in your Livewire component, ensure that you have an array ($lines) where each new line added will store an item.

Please or to participate in this conversation.