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;
    });
j0k
  • 22,600
  • 28
  • 79
  • 90
Tommy
  • 265
  • 1
  • 6
  • 15

2 Answers2

26

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.

alexw
  • 8,468
  • 6
  • 54
  • 86
  • 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) {` – Mark Sep 02 '16 at 17:37
  • @alexw, what about multiple selected items ? check this jsfiddle : https://jsfiddle.net/xqhp0z0x/27/ – chirag satapara Oct 05 '17 at 06:34
  • @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 https://github.com/select2/docs, I can document this. – alexw Oct 05 '17 at 16:49
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});
Tom
  • 641
  • 2
  • 8
  • 21