Select2 in multiple fields with the same name

Asked

Viewed 379 times

1

I am making an order registration page, where you can register several products.

To register the products users have the options to Produto, quantidade, valor, subtotal, if you want to add one more product, it has a function that adds one more row of these fields. campos do produto

My problem is I’m using the Select2 to search the products in the database, however, Select2 only works in the first product field, if I add 1 more product, it does not work the Select2.

múltiplos produtos

You may notice that the product fields have a difference, as one with the Select2 and another no.

The code JS that I’m using for this quest is this:

$( "#produto" ).select2({        
    ajax: {
        url: "modulos/orcamentos_funcao.php?buscar=produto",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term // search term
            };
        },
        processResults: function (data) {
            // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data
            return {
                results: data
            };
        },
        cache: true
    },
    minimumInputLength: 1
});

In short, I need a dynamic product search.

2 answers

2


I had a similar problem a long time ago. At the time, I gave up searching, but I believe that with the "on" feature of jQuery you can restart Select2 for dynamically added Elements.

Try adding "manually" Select2 inside the clone of your element.

  • can give 1 example please?

0

I had a problem like this and I found a functional solution that when you add a new item in the list that is when you download the Select2, you "Destroy" the Select2 and start again.

// inicia componente select
    $(".arrCentroCusto").select2({
        tags: true
    });

$(".adicionarCampo").click(function () { // clona a linha do select
        $('.arrCentroCusto').select2("destroy"); // destroi o select2 para não bugar
        novoCampo = $("tr.linhas:first").clone(); // clona a linha
        novoCampo.find("input").val(""); // tras a nova linha como null
        novoCampo.insertAfter("tr.linhas:last"); //bota a nova linha em baixo
        removeCampo(); 

        $('.arrCentroCusto').select2();//inicia o select2 novamente
    });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.