I tried many things.
i cant initialize default selected items.
The values always "undefined".
Can anyone please help me?
i create de select2, and add options for select.
var selected = [{
"id": 50270924,
"full_name": "zquestz/s",
"description": "Open a web search in your terminal.",
"language": "Go"
}, {
"id": 30494317,
"full_name": "haosdent/s",
"description": "s is a tool for ssh like z for cd",
"language": "Shell"
}];
var $gitElement = $(".select2").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
data:selected,
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: function(repo) {
console.log("res", repo, this);
return '<div class="select2CompanyName">'+repo.full_name+'</div>' +
'<div class="select2CompanyTitle">'+repo.language+'</div>' +
'<div class="select2CompanyTitle">'+repo.description+'</div>';
},
templateSelection: function(repo) {
console.log("sel", repo, this);
return '<div class="select2CompanyResult">' +
'<div class="select2CompanyName">'+repo.full_name+' <br>'+ repo.language +'</div>' +
'<i class="fa fa-pencil-square-o"></i>' +
'</div>';
}
});
for(var i in selected) {
$(".select2").append('<option value="'+selected[i].id+'" selected="selected"></option>');
}
$(".select2").trigger("change");
this version:
jsfiddle
ugly solution would be:
for(var i in selected) {
$(".select2").append('<option value="'+selected[i].id+'" selected="selected">'+JSON.stringify(selected[i])+'</option>');
}
here
working, but ugly
there got a simple way to fix it, u just need to move your template logic to processResults, code should be something like :
function displayItem(repo) {
return {
id : repo.id,
text : '<div class="select2CompanyName">'+repo.full_name+'</div>' +
'<div class="select2CompanyTitle">'+repo.language+'</div>' +
'<div class="select2CompanyTitle">'+repo.description+'</div>'
};
}
....
processResults: function (data, page) {
return {
results: $.map(data.items, displayItem);
};
},
Cost me sometime to find the issue.. I upgrade select2 version to 4.0.2. check fiddle here
Related
Please, help.
html:
<select id="select-client" class="form-control" style="width: 350px;"></select>
js:
$("#select-client").select2({
ajax: {
url: _app.url + "finduser",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 2,
templateResult: formatClientRepo,
templateSelection: formatClientRepoSelection,
placeholder: "Enter user name"
});
And as result I've received this: http://prntscr.com/76jxvi
I found many variants, such as empty option in select, or write placeholder in select, but nothing.
https://jsfiddle.net/xqhp0z0x/1/
in this example if we delete || repo.text from formatRepoSelection it will not work. Because the repo.text is placeholder.
P.S. select2 4.0 do not need to empty option tag for placeholder working
Refer to https://select2.github.io/examples.html, text "Searching" is shown when the remote data is loading. However, I don't know why "undefined" is shown in my case.
This is the css file.
<div class="col-sm-9">
<select class="js-data-example-ajax form-control" style="width:100%;">
<option value="select2/select2" selected="selected">select2/select2</option>
</select>
</div>
And the setting of ajax call
$(".js-data-example-ajax").select2({
ajax: {
url: "/search/products",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
minimumInputLength: 1,
templateResult: formatProduct,
templateSelection: formatProductSelection
});
Result:
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = '<div class="clearfix">' +
'<div class="col-sm-1">' +
'<img src="' + repo.owner.avatar_url + '" style="max-width: 100%" />' +
'</div>' +
'<div clas="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-6">' + repo.full_name + '</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
'<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
'</div>';
if (repo.description) {
markup += '<div>' + repo.description + '</div>';
}
markup += '</div></div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.full_name || repo.text;
}
$ajax.select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
complete code which loads repositories in select 2 you can alter this code according to your requirements
my select box with multiple select
<select id="to_users" name="to_users" class="form-control js-data-example-ajax" multiple="multiple">
</select>
you can format results
processResults: function(data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: $.map(data, function(obj) {
return { id: obj.user_id, text: obj.name };
})
//results: data
};
},
if you are formatting results to select2 behaviour then disable code
/* escapeMarkup: function(markup) {
return markup;
}, // let our custom formatter work
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page*/
Please try
function formatRepo(repo) {
if (repo.value == undefined) {
repo.value = 'Loading...'
}
var markup = '<div class="clearfix">' + repo.value + '</div>'
return markup;
}
There is a possible workaround for the above issue. Feel free to make comments.
Here is the code I've written before, let say the return JSON is {"items":[{"id":1,"name":"Product1"},{"id":2,"name":"Product2"}]}
var formatProduct = function(data){
return '<div>'+(data.name)+'</div>';
}
I've modified the code as follow and the 'Searching...' text shows again:
var formatProduct = function(data){
return '<div>'+(data.name || data.text)+'</div>';
}
In select2.js, line 798, when the data is remotely loading
this.template(data, option);
this.template directs to select2.js line 1058
Results.prototype.template = function (result, container) {
var template = this.options.get('templateResult');
container.innerHTML = template(result);
};
// result is an object indicating whether the data is loading.
// {disabled: true, loading: true, text: "Searching…"}
the template here takes the custom parameter 'templateResult' and generate the text, therefore, the custom function must contain data.text, otherwise it returns underfined.
In my case it was the formatProduct function (it has a different name in my code, but it's the same thing).
Let's say you call formatProduct for templateResult:
templateResult: formatProduct
In this case you have to check what formatProduct returns, like:
function formatProduct(product) {
return product.name || product.text;
}
In my case I was returning always product.name and the "Searching" text was under product.text, so I had to check to display it when no product was being found yet.
I am using select2 select box to populate and show some server data. Most of it works fine as I am able to get the results and populate the combo box. But when I type in the search box, the selection doesn't narrow down the the closest match.
I found the problem was because the backend URL doesn't support searching based on the string provided, while select2 keeps making multiple search request to backend, based on user entered text. The legacy backend code returns results in one shot, which is populated into the combobox the first time.
My question is, how do I get the the select box to focus to the closest matching result, without making multiple Ajax calls. I want the search to happen in the results which are already fetched.
Thanx to anyone helping me out on this.
My ajax call is like below, if this helps...
select2: {
placeholder: 'Select Next Plan Id',
allowClear: true,
id: function (item) {
return item.id;
},
ajax: {
type: 'GET',
dataType: "jsonp",
url: "http://172.16.7.248:8480/app/gui?action=1&type=11",
data: function (term, page) {
return { search: term };
},
results: function (data, page) {
return { results: data.aaData };
},
success : function(data, status, xhr) {
var html = "<option value=''>None</option>";
$.each(data.aaData, function(i, item) {
html += "<option data=" + JSON.stringify(item.id) + " value=" + item.id + "'>" + item.id + "</option>";
});
$('#nextplanid').html(html);
self.prop('data-loaded', 'true');
},
error : function(data, status, xhr) {
}
},
formatResult: function (item) {
return item.id;
},
formatSelection: function (item) {
return item.id;
},
initSelection: function (element, callback) {
return $.get('/getText', { query: element.val() }, function (data) {
callback(data);
});
}
},
I'm still finding my way with Backbone and I've always use Prototype instead of jQuery in the past so please forgive me if I'm doing something stupid.
I'm trying to develop a UI containing several connected unordered lists where each sortable list is represented by a separate Backbone collection. I'm using ICanHaz and Mustache templates but that's not of importance for my question.
When dragging items between the lists, how would I best achieve the automatic updating of the collections (remove a model from one and insert it into another)? I'm currently trying to use the receive and remove methods in the jQueryUI Sortable interaction — am I at least on the right lines?
var WS = {};
(function(ns) {
ns.Item = Backbone.Model.extend();
ns.Content = Backbone.Collection.extend({
model: ns.Item,
url: location.href,
initialize: function(el) {
this.el = $(el);
this.deferred = this.fetch();
},
recalculate: function() {
var count = this.length;
this.el.next(".subtotal").html(count);
},
setOrder: function() {
$.ajax({
url: this.url + "/reorder",
type: "POST",
data: "tasks=" + $(this.el).attr("id") + "&" + this.el.sortable("serialize")
});
}
});
ns.ContentRow = Backbone.View.extend({
tagName: "li",
className: "item",
events: {
"click .delete": "destroy"
},
initialize: function(options) {
_.bindAll(this, "render", "destroy");
this.model.bind("change", this.render);
this.model.view = this;
},
render: function() {
var row = ich.item(this.model.toJSON());
$(this.el).html(row);
return this;
},
destroy: function() {
if (confirm("Really delete?")) {
this.model.destroy({
success: function(model, response) {
$(model.view.el).remove();
},
error: function(model, response) {
console.log(response);
}
});
}
}
});
ns.ListView = Backbone.View.extend({
initialize: function(collection) {
this.el = collection.el;
this.collection = collection;
this.collection.bind("add", this.addOne, this);
_.bindAll(this, "addOne");
this.el.sortable({
axis: "y",
connectWith: ".tasks",
receive: _.bind(function(event, ui) {
// do something here?
}, this),
remove: _.bind(function(event, ui) {
// do something here?
}, this),
update: _.bind(function(event, ui) {
var list = ui.item.context.parentNode;
this.collection.setOrder();
}, this)
});
},
insert: function(item) {
var prefix = this.el.parentsUntil('ul').parent().attr("id"),
view = new ns.ContentRow({
model: item,
id: prefix + "_" + item.id
});
this.el.append(view.render().el);
},
addOne: function(item) {
if (item.isNew()) {
item.save({}, {
success: _.bind(function(model, response) {
// I should set id from JSON response when live
model.set({ id: this.collection.length });
this.insert(model);
}, this)
});
} else {
this.insert(item);
}
},
addAll: function() {
this.collection.each(this.addOne);
},
render: function() {
this.collection.deferred.done(_.bind(function() {
this.addAll();
}, this));
}
});
ns.AppView = Backbone.View.extend({
lists: [],
initialize: function(holder) {
holder.find("ul").each(_.bind(function(index, list) {
var Items = new WS.Content(list),
App = new WS.ListView(Items);
App.render();
this.lists.push(Items);
}, this));
}
});
})(WS);
$(document).ready(function() {
var App = new WS.AppView($("#tasks"));
});
You are on the right track. You will probably want to add the id of each sortable element into the template somewhere. Then when you receive the event, you know which model to add or remove from the collection. For example add...
<div data-id={{id}}> ... my thing ... </div>
And in the sortable call get the target's id attribute and call Collection.add() or remove()
Just use Backbone.CollectionView.. it has this functionality built in out of the box.
var listView = new Backbone.CollectionView( {
el : $( "#list1" ),
sortable : true,
sortableOptions : {
connectWith : "#list2"
},
collection : new Backbone.Collection
} );
var listView = new Backbone.CollectionView( {
el: $( "#list2" ),
sortable : true,
sortableOptions : {
connectWith : "#list1"
},
collection : new Backbone.Collection
} );
Hi I got a problem with change event.
By documntation there should be object ui.item
After an item was selected; ui.item refers to the selected item. Always triggered after the close event.
But when I try it ui.item is undefined :( I want unset s_town_id when input in autocomplete doesn't match with data from script.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
// ui.item is undefined :( where is the problem?
$("#s_town_id").val(ui.item.id);
}
});
});
I find out solution where I testing event.originalEvent.type if it is meneuselected or not and after fail I unset s_town_id. But any better solution is still wellcome.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
try
{
if(event.originalEvent.type != "menuselected")
{
// Unset ID
$("#s_town_id").val("");
}
}
catch(err){
// unset ID
$("#s_town_id").val("");
}
}
});
});
if ui.item is not defined that means your json source is not well formed.
You have to send a json source like this:
[{"label":"Jean","value":1},{"label":"carl","value":2}]
You can add more key to the array but at least you have to set "label" and "value".
Check the json string.
Also I reckon you to use the last version of autocomplete 1.8.1 at the moment