Master Detail with select2

2

I'm trying to make a master detail

One of its inputs is Select2 , but it does not generate Select2 , because it is only generated when the script finishes reading, and the second way I did, was to do a function that calls the select2, for it to always be generated, however it ends up clearing the others already filled

Well my code looks like this:

<button type="button" id="add">Adicionar</button>
 <div class="vinculo">
</div>

    $(function () {
        $("#add").on("click", function () {
            var i = $('.vinculo input').size() + 1;
            $('<input type="text" name="vinculo[' + i + ']" id="select2vinculo' + i + '" />').appendTo(".vinculo");
        });
    });

and my select2:

var pageSize = 10;
        $('.select2vinculo').select2(
        {
            minimumInputLength: 0,
            allowClear: true,
            ajax: {
                quietMillis: 150,
                url: '@Url.Action("Vinculos", "Select2", new { area = "" })',
                dataType: 'json',
                data: function (filtro, page) {
                    return {
                        pageSize: pageSize,
                        pageNum: page,
                        Filtro: filtro
                    };
                },
                results: function (data, page) {
                    var more = (page * pageSize) < data.total;
                    return {
                        results: data.result,
                        more: more
                    };
                }
            },
            initSelection: function (element, callback) {
                var vinculo = $('#select2vinculo').val();
                if (vinculo !== null && vinculo > 0) {
                    $.ajax({
                        url: '@Url.Action("BuscaVinculoId", "Select2", new { area = "" })',
                        dataType: "json",
                        data: { Id: vinculo },
                        success: function (data) {
                            callback(data);
                        }
                    });
                }
            },
        })

I also do not know how I will capture all the values when editing, because the initSelection function takes the value of select2 and calls to set the value of it, which is what makes the code, since I have to capture all to leave selected , ie "# select2link + i, where i is generated by" Add "input

 initSelection: function (element, callback) {
                    var vinculo = $('#select2vinculo').val();

Does anyone have a solution? whether in jquery, knockout, or any other way to do a master details

I'm grateful.

    
asked by anonymous 19.12.2014 / 18:42

2 answers

1

Your question is a bit difficult to understand, so I'll assume first by following the code's problems:

You want to add new combos for every time you click on #add , if this is what the @iuristona said is right, the correct one is to use <select> and not <input> , since "select2" works with selects.

  • Note: .select2 must be executed after .appendTo
  • Note: Instead of $('.vinculo input').size() + 1 you should capture the selects, like this: $('.vinculo select').size() + 1
  • Note: .size is deprecated, use .length

The code should look something like this:

<button type="button" id="add">Adicionar</button>
<div class="vinculo"></div>

<script>
    $(function () {
        $("#add").on("click", function () {
            var i = $('.vinculo select').length + 1;//.size() está em dezuso
            var s = $('<select name="vinculo[' + i + ']"></select>');

            s.appendTo(".vinculo");

            //Select2 deve ser executado depois do appendTo, por que ele utiliza o elemento parentNode
            s.select2();
        });
    });
</script>

To capture all the selects, something like $(".vinculo select[name^=vinculo]") , you can also use an object (json) and then send via ajax as an "update", something like:

var els = $(".vinculo select[name^=vinculo]");
var dados = {};

els.each(function() {
    dados[$(this).attr("name")] = $(this).val();
});

$.ajax({
    "type": "POST", //Usando metodo POST
    "url": URL_UPDATE,//Sua url de update
    "data": dados //Envia os dados
}).then(function(response) {
    //Resposta do servidor
    console.log(response);
}).fail(function(err) {
   console.log("Erro:", err);
});

To capture the results with ASP.NET, you can use the language of your choice, in which case I'll show an example with c# :

string[] valores = Request.Form.GetValues("vinculo");
foreach (string v in valores) {
}

If you return NULL , use this way:

string[] valores = Request.Form.GetValues("vinculo[]");
foreach (string v in valores) {
}
    
27.12.2014 / 21:02
1

So I understand you want every click on #add to append a new select with select2.

First of all, I might be wrong, but I only used select2 with a select element and not input . That's right, do you want a <input type=text /> ?

Next, you should call each click o select2(); like this:

$(function () {
    $("#add").on("click", function () {
        var i = $('.vinculo input').size() + 1;
        var $select = $('<select name="vinculo[' + i + ']" id="select2vinculo' + i + '" />')
        .select2({ 
           //aqui as definições do seu select2 
        });

        $select.appendTo(".vinculo");
    });
});
    
27.12.2014 / 13:21