Value as Object when selecting item in Select2

2

The Select2 plugin works normally, the only problem is when I make the item selection the value set in the hidden (mandatory to bring data via AJAX) stays as [Object Value] and not the value specified by the format.

Follow form:

    <form id="Teste" method="get" action="">
        <input type="hidden" id="e6" name="e6" class="select2" style="width: 600px;" />

        <input type="submit" value="Enviar" />
    </form>

Value in input hidden after selection:

<input type="hidden" id="e6" name="e6" class="select2 select2-offscreen" style="width: 600px;" tabindex="-1" title="" value="[object Object]">

JavaScript to create Select2:

function formataResultado(item) {
    return item.Text;
}

function formataSelecao(item) {
    return item.Value;
}

$("#e6").select2({
    placeholder: "Selecionar fornecedor",
    minimumInputLength: 0,
    id: function(data){return {id: data.id};},
    allowClear: true,
    ajax: {
        url: "http://localhost:1396/Lista/_GetDropDownListFornecedor",
        dataType: 'jsonp',
        quietMillis: 300,
        data: function (term, page) {
            return {
                searchString: term,
                pageSize: 60,
                pageIndex: page,
            };
        },
        results: function (data, page) {
            return {results: data.results, more: (page * 60) < data.total };
        }
    },
    formatResult: formataResultado,
    formatSelection: formataSelecao,
    dropdownCssClass: "bigdrop",
    escapeMarkup: function (m) { return m; }
});

JSON returned by the AJAX query made by Select2:

{"results":[{"Selected":false,"Text":"Cezar Barbara","Value":"724"},
 {"Selected":false,"Text":"Cezar Barbara","Value":"765"}],
 "total":82}
    
asked by anonymous 24.07.2014 / 15:41

1 answer

2

Your problem is in the id function:

id: function(data){return {id: data.id};},

It should not return an object, but the value itself to be assigned to the hidden field (which by the way is Value , not id ):

id: function(data){return data.Value;},

Probably the previous function referred to some older version of Select2 (this explains its [object Object] - because this is the default string representation of any object, and how its function id was returning an object. .).

Example in jsFiddle (adapted). By the way, by doing this you are free to display user-friendly value in your formataSelecao function, you do not need to display Value on the screen.

    
24.07.2014 / 17:15