Select2 in several fields with the same name

1

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

In order to register the products the users have the options of Produto, quantidade, valor, subtotal , if they want to add another product, it has a function that adds one more line of these fields.

MyproblemisthatI'musingSelect2tofetchtheproductsinthedatabase,butSelect2willonlyworkinthefirstproductfield,soifIaddanotherproduct,itdoesnotwork.

Youmaynoticethattheproductfieldshaveadifference,sinceonewithSelect2andanothernot.

TheJScodeI'musingforthissearchisthis:

$("#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 search for products.

    
asked by anonymous 23.10.2018 / 18:14

2 answers

2

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

Try to add select2 "manually" within the clone of your element.

    
23.10.2018 / 19:33
0

I had a problem like that and I found a functional solution that when you add a new item to the list that is when buga Select2, you "destroy" 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
    });
    
13.11.2018 / 16:58