Master Detail with Select2

Asked

Viewed 601 times

2

I’m trying to make a master Detail

One of its inputs is a Select2, But it does not generate the Select2, until why it is generated only when finished reading the script, and the second way I did, was to make a function that calls Select2, so it will always be generated, but it ends up zeroing the others already filled

Well my code is 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 Lect2:

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);
                        }
                    });
                }
            },
        })

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

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

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

I am grateful.

  • could illustrate your example better, with a screen print for example, to get a sense of how and the result.

  • I’m in doubt of some things here var vinculo = $('#vinculo').val(); you call an element with "ID", but understand that maybe you are trying to catch or <div class="vinculo"> or "inputs" within the <div class="vinculo">, tell me what exactly this method should capture? It is at this point that you want to pick up all inputs and send them by ajax?

  • @Guilhermenascimento in my example I have a div with class="link" but I have inputs that are generated links[1]

  • Yes it’s clear Rod, but you’re using #vinculo, It doesn’t capture elements like this: <div class="vinculo"> he captures one element like this <div id="vinculo">, in your html there is no DIV with the ID link, so I don’t see how this could work. If you can be more clear you may be able to understand your code, so it has not yet been possible to reproduce the code and understand its need, I look forward to.

  • Hi William, I think there in my example I did not see, in the case you mentioned, it takes the input element, and its value to leave already filled (in case of editing the record) there Lect2 looks for the record as the input Val, I think in the example was not clear, I will edit

  • Rod a tip, when sending message to a user in the comments use the @username, why else the message does not arrive in the Inbox, I’m trying to read your question, but she’s very confused, could you please review the text? Grateful

  • @Rod I think I got it, the element <select> already exists, you want to add new items (<option>) for him? That’s it?

Show 2 more comments

2 answers

1

From what I understand you want every click on #add append a new select with Select2.

First of all, I may be wrong, but I only used select2 with an element select and not with input. That’s right, you want one <input type=text />?

Then you should call each click the select2(); thus:

$(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");
    });
});
  • Just one comment, you can’t use .select2 before .appendTo why it needs elements such as .parentNode in order to generate other elements.

1


Your question is a little difficult to understand, so I’ll assume first by following the code problems:

You want to add new combos for each time you click on #add, if so, then what @iuristona said is right, the correct is to use <select> and not <input>, because "Select2" works with "selects".

  • Note: .select2 must be executed after .appendTo
  • Note: Instead of $('.vinculo input').size() + 1 you must capture the "selects", so: $('.vinculo select').size() + 1
  • Note: .size is in disuse, 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 selects, it would take something like $(".vinculo select[name^=vinculo]"), you can also use an object (json) and later 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 you prefer, in case I will show an example with c#:

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

Return NULL, use this way:

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

Browser other questions tagged

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