Set data in Select2 after insert with AJAX
Asked Answered
J

2

12

i'm using the Select2 with AJAX (the code below):

$(".select2-ajax").select2({
        placeholder: "Search user",
        minimumInputLength: 1,
        ajax: {
            url: $('#url-search-client').val(),
            dataType: 'json',
            type: 'post',
            data: function (term, page) {
            return {
                filter: term
            };
            },
            results: function (data, page) {
            return {results: data};
            }
        },
        width : '50%',
        formatInputTooShort: function () {return 'Informe mais caracteres'; },
        formatResult: formatResultSelectAjax, // omitted for brevity, see the source of this page
        formatSelection: formatSelectAjaxValue, // omitted for brevity, see the source of this page
        dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
    });

Well, if not found client, the user can be use a button to open a modal and add the new client, is possible use the return(json with id and namae) of new client and put the data (like name) into the select2 as selected?

$('.btn-form-client').click(function() {
        $.ajax({
            url: $('#frm-client').attr('action'),
            dataType: 'json',
            type: 'post',
            data: $('#frm-client').serialize()
        }).done(function (data) {
            $('#modal-client').modal('hide')
        });
        return false;
    });
Jarlathus answered 14/1, 2013 at 2:35 Comment(1)
Could you make this work?Braunschweig
M
27

Starting in v4.x, select2 no longer uses the hidden input field. Instead, you create a new Option and append it to your select element:

var newOption = new Option(data.name, data.id, true, true);
$(".select2-ajax").append(newOption).trigger('change');

The combination of the true arguments and trigger('change') will make sure your new <option> is automatically selected after being added.

See my codepen for a complete working example.

Marybethmaryellen answered 14/4, 2016 at 1:40 Comment(3)
If you want to add an option with spaces, the jquery lookup needs to be fixed to surround the option value with single quotes: if ($("#state").find("option[value='" + newStateVal + "']").length) {Alisonalissa
@alexw, what about multiple selected items ? check this jsfiddle : jsfiddle.net/xqhp0z0x/27Individualize
@chiragsatapara you can pass an array of values to .val, but you need to do all of this after you initialize the Select2. If you open an issue on github.com/select2/docs, I can document this.Marybethmaryellen
W
1

I managed to make it work. After POST in jQuery, i get a JSON with the new data and set the hidden input and the select ('.select2-ajax')

$('#client=id').val(data.id);
$('#modal-solicitante').modal('hide'); //This is my
$(".select2-ajax").select2('data', {id: data.id, name: data.name, email: data.email});
Whitver answered 7/3, 2014 at 18:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.