0
votes


I have new problem with my Select2 option. I can't clear my select box. As in JSFiddle I do 'select' for my data. The problem lies in the fact that I can not remove the last element, or clear the whole field in my web portal, but in JSFiddle everything looks ok. My portal gives me error "Type Error: a is null" and I don't know why.

Here is my code:

$.getJSON(url, function (data){
    $("#mySelect").select2({
        data:data,
        placeholder: "Select options",
        templateSelection: function(val) {
            return val.text;
        }
    });
});

And my select:

<select id="mySelect"></select>

The problem disappears when I use other solution but then I can not invoke the relevant data for 'templateSelection'. In this solution I create options for my select, and simple use select2 but as You can see for the field 'data.version' I have the answer "undefined"

Code:

var data=[
  {id:1, text: "sample_1", version: "1"},
  {id:2, text: "sample_2", version: "2"}];

$.each(data, function(i,x){
    $('#mySelect').append($('<option>', {
    value: x.id,
    text: x.text
    }));
});

$("#mySelect").select2({
    templateResult: function(data) {
    return data.text + ' ' + data.version;
  }
});

JSFIDDLE

Any sugestion why this solution work in jsfiddle, but not in my portal?

1
You don't have variable 'a' in your code. Maybe you made misprint?Maxim Goncharuk
Yeah, but I got this error in jquery-2.1.3.min.jsradek.
Do you have the newest version of select2.full.min.js?Maxim Goncharuk

1 Answers

0
votes

var data=[{id:1, text: "sample_1", version: "1"},{id:2, text: "sample_2", version: "2"}]

$.each(data, function(i,x){
   $('#mySelect').append($('<option>', {
                value: x.id,
                text: x.text+" "+x.version,
                
            }));
});
$("#mySelect").select2({
  templateResult: function(data) {
    return data.text;
  }
});

when $ function is used to create element it can only accept html attributes of that element