Proper usage of jQuery select2's initSelection callback with remote data - javascript

I use jQuery select2 plugin in order to retrieve postcodes using the provided ajax callback function as follows:
$(document).ready(function() {
$("#postcodes").select2({
placeholder : "Search for a postcode",
multiple : true,
minimumInputLength : 3,
ajax : {
url : "/bignibou/utils/findGeolocationPostcodeByPostcodeStartingWith.json",
dataType : 'json',
data : function(term) {
return {
postcode : term
};
},
results : function(data) {
console.log(data);
return {
results : $.map(data, function(item) {
return {
id : item.id,
text : item.postcode
};
})
};
}
}
});
});
Once two postcodes are selected I get the resulting hidden input in the DOM:
<input type="hidden" class="bigdrop select2-offscreen" id="postcodes" style="width:600px" name="familyAdvertisement.postcodes" value="4797,4798" tabindex="-1">
The issue I have is that once the form is redisplayed (for instance in the event of some other controls being in error), the selections (i.e. the two postcodes and especially the text) don't show in the form although the hidden input does have the two values (i.e. 4797 and 4798, which are the ids for the postcode).
I am not sure if I have to do another ajax round trip when the form is redisplayed or if there is a better way to go.
Can anyone please advise?

The initSelection method has to pass the values which has to be present in the select2
Ex:
$("#postcodes").select2({
placeholder : "Search for a postcode",
multiple : true,
minimumInputLength : 1,
data:[],
initSelection : function (element, callback) {
var data = [{id:1,text:'bug'},{id:2,text:'duplicate'}];
callback(data);
}
}).select2('val', ['1', '2']);
Demo: Fiddle

Related

UI-Select2 binding to object instead of property of object

I am using ui-select2, version 3.5.2, trying to do a single select, type-ahead and retrieve from REST api, drop down list.
It looks like it is working except for one major issue, which is that, the ng-model's property gets set to an object {Id: "some id", text: "some text"} instead of the actual Id property. I cannot figure out how to tell ui-select2 control to set the ng-model property to the "Id" field of the object, instead of the whole object.
I have tried various hacks with watchers but didnt get anywhere. I am sure there is something that I am missing because this is something that should be possible easily.
Here is my javascript code:
$scope.selectOptions = {
placeholder: '- Select Value -',
allowClear: true,
minimumInputLength: 2,
initSelection: function (element, callback)
{
if ($scope.myobj && $scope.myobj.Id && $scope.myobj.Id !== '00000000-0000-0000-0000-000000000000')
{
$.ajax("../../api/objs/" + $scope.myobj.Id).done(function (data) {
var res = $(data).map(function (i, o) {
return {
id: o.Value,
text: o.Display
};
}).get();
callback(res[0]);
});
}
},
ajax:
{
type: "GET",
url: function (term) {
return ["../../api", "objs", encodeURIComponent(term)].join("/");
},
dataType: "json",
contentType: "application/json",
cache: false,
results: function (data, page) {
return {
results: $(data).map(function (i, o) {
angular.extend(o, {
id: o.Value,
text: o.Display
});
return o;
}).get()
};
}
}
}
Here is my html code:
<div ui-select2='selectOptions' ng-model="myobj.Id" style="width:215px" />
I got around this by binding to a separate property and then adding a ng-change on my div and syncing the binding property's id field to actual property on my object.

Select2 inserts an empty text option in the dynamic list

I am using Select2 with Jquery-editable and encountering an abnormal behavior of Select2, what I am doing is displaying editable table of information using ejs template, and as user clicks on CBA opens up a select2 box which have the originally selected result, and then user can add or delete options in it, options comes from Database source, and when user selects an options it adds an empty option in database with the selected option , the array looks like this
[ "ABCD", "ONAB", "" , "BCNU" ]
I read somewhere about allowClear: true and add a placeHolder but It doesn't helped me at all. As everything is done dynamically I can't find where that empty option is added.
Code is below:
Ejs/HTML code for Select 2
<tr>
<td width="40%">Select CBA(s)</td>
<td>
<a class="cbaSelectUnit" data-emptytext="Select CBA(s)" data-original-title="Select CBA(s)" data-type="select2"></a>
</td>
Javascript for Select 2
$("a[data-name='Cba']").editable({
showbuttons: 'false',
emptytext: 'None',
display: function(values) {
var html = [];
html.push(values);
$(this).html(html);
},
select2: {
multiple: true,
allowClear: true,
placeholder: "Select CBA(s)",
ajax: {
// url is copied from data-source via x-editable option-passing mechanism
dataType: 'json',
// pass the '?format=select2' parameter to API call for the select2-specific format
data: function(term, page) {
return {
deptId: departmentId,
format: 'select2'
};
},
// transform returned results into the format used by select2
results: function(data, page) {
return {
results: data
};
}
},
// what is shown in the list
formatResult: function(cba) {
return cba.text;
},
// what will appear in the selected tag box
formatSelection: function(cba) {
return cba.text;
},
// rendering id of the values to data.value requirement for Select 2
id: function(cba) {
return cba.value;
},
// what is shown in the selected-tags box
initSelection: function(element, callback) {
var id = $(element).val(),
result = id.replace(/^,\s*$/, ',').split(",").map(function(v) {
return {
id: v,
text: v
};
});
callback(result);
}
}
});
Format in which Code is returned from the database:-
Facility.findOne({ _id: department.Facility }, function(err, facility) {
if (err) {
res.send(500, err);
} else if (!facility) {
res.send(404, 'Facility not found');
} else if (req.query.format && req.query.format === 'select2') {
var result = facility.Cba.map(function(c) {
return { value: c, text: c };
});
res.json(result);
}
});
Image showing an empty box added by itself
How Array looks after I edit
So it was just a simple syntax error, I was doing found out by myself,
I was returning cba.value as id, but the initSelection was returning
{id: v, text: v}
it should be value & text instead of id & text.
// what is shown in the selected-tags box
initSelection: function(element, callback) {
var id = $(element).val(),
result = id.replace(/^,\s*$/, ',').split(",").map(function(v) {
return {
value: v,
text: v
};
});
callback(result);
}

Extending kendo multiselect and working with MVVM

I'm trying to extend a kendo multiselect so that it has a default data source as well as templates. It's all working except the pre-loaded values in the MVVM object. When I start updating the exented multiselect, the value of the MVVM gets updated, the initial items are just not pre-loaded:
kendo.ui.plugin(kendo.ui.MultiSelect.extend({
init: function(element, options) {
var ds = new kendo.data.DataSource({
type: "json",
serverFiltering: true,
transport: {
read: {
url: "/SecurityEntities",
dataType: "json"
},
parameterMap: function(data) {
return {
prefixText: '',
count: 5,
getUsers: true,
getGroups: false
};
}
},
schema: {
data: function(data) {
console.log($.parseJSON(data));
return $.parseJSON(data);
}
}
});
options = options == null ? {} : options;
options.itemTemplate = "...";
options.tagTemplate = "...";
options.dataSource = ds;
kendo.ui.MultiSelect.fn.init.call(this, element, options);
},
options: {
name: 'EntityMultiSelect'
}
}));
kendo.data.binders.widget.entitymultiselect =
kendo.data.binders.widget.multiselect;
Then my html is:
<div data-bind="value: machine.Managers" data-role="entitymultiselect"
data-delay="400" data-animation="false"
data-placeholder="Select users to notify"></div>
And I am binding the whole container to the page's viewModel object.
I've seen other people have issues with this very problem and added the
kendo.data.binders.widget.entitymultiselect =
kendo.data.binders.widget.multiselect;
(And yes that does seem like a bug)
But it still doesn't work.
When there are already values in Machine.Managers, it doesn't load them. However, if I add values to the multiselect, they get added to Machine.Managers .
EDIT:
I've added a live example
At least in your demo it's a trivial problem: your data-value-field is wrong. As a result, the binder can't match the selected elements.
Instead of
<div data-role="entitymultiselect"
data-bind="value: selected"
data-value-field="ProductId"></div>
you need
<div data-role="entitymultiselect"
data-bind="value: selected"
data-value-field="ProductID"></div>
(working demo)
Since you're not defining the value field in the code in your question, it might be the same issue.

Select2 - avoiding duplicates tags

How can I avoiding duplicates tags in Select2 input?
When I type tag name on the keyboard string is added to input field, but when I select tag from dropdown list (results from the database) the id is added to input (look at console.log on screenshot). So I can select tag from list and add the same tag from keyboard.
Moreover, I need the text of tags, not id from dropdown list while submit a form.
Full resolution
HTML:
<input type="hidden" id="categories" name="categories" style="width:100%" value="${categories}">
JS:
$("#categories").select2({
tags: true,
tokenSeparators: [","],
placeholder: "Dodaj",
multiple: false,
minimumInputLength: 3,
maximumInputLength: 50,
maximumSelectionSize: 20,
ajax: {
quietMillis: 150,
url: '${request.route_url("select2")}',
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page,
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {results: data.categories, more: more};
}
},
initSelection: function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
createSearchChoice: function (term) {
return { id: term, text: term };
},
}).change(function (e) {
if (e.added) {
console.log($("#categories").val())
console.log(e)
}
});
Have same problem, but I figured it out to find a way around.
I'm getting text and ids, but on the server side I'm creating from given id new objects, which are well read.
$tagsArray = explode(',', $tagNames); // it contains of my input select2 value (with ids)
foreach ($tagsArray as $tag)
{
if (is_numeric($tag))
{
$tags->append(TagQuery::create()->filterById($tag)->findOneOrCreate());
}
elseif (!empty($tag))
{
$tags->append(TagQuery::create()->filterByName($tag)->findOneOrCreate());
}
}
Hope it helps.
at first use select 2
and then do this:
$("select").change(function() { var tr = $(this).closest("tr");
tr.find("select option").attr("disabled",""); //enable everything
//collect the values from selected;
var arr = $.map
(
tr.find("select option:selected"), function(n)
{
return n.value;
}
);
//disable elements
tr.find("select option").filter(function()
{
return $.inArray($(this).val(),arr)>-1; //if value is in the array of selected values
}).attr("disabled","disabled"); });

Get user input from single select box using Select2

Issue
I just started using Select2 (http://ivaynberg.github.io/select2/) and I am trying to do a basic task.
I have a select box that has, for example, 3 items in it. I want to be able to have the user either select 1 of the 3 results or type in their own result and then eventually, on submit, it will submit whatever value is in the box.
What I've Tried
<input style="width: 200px;" type="hidden" id="foo" />
<script type="text/javascript">
$(document).ready(function () {
$("#foo").select2({
query: function (query) {
var data = { results: [{ text: 'math' }, { text: 'science' }, { text: 'english' }] };
data.results.push({ text: query.term });
query.callback(data);
}
});
});
</script>
The code above allows me to see the 3 results and type in a result myself. But I am unable to get the typed in result to "stick" when I click away, hit enter, or select the result I just typed in. Same goes for the select options, but I am most concerned with the user inputted text.
Here's what it looks like:
The parameter createSearchChoice allows you to do just what you want. Here is an example:
<script type="text/javascript">
$("#foo").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};
}
},
multiple: false,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
</script>
Taken from a closed issue at: https://github.com/ivaynberg/select2/issues/201
Fiddle: http://jsfiddle.net/pHSdP/2/
Also, make sure you add a name to the input, otherwise you won't see the value at server side
<input style="width: 200px;" type="hidden" id="foo" name="foo" />
Just a quick note for anyone else who's having a different data input. In case the console says " this.text is undefined ", make sure you check your text tag, like this:
<script type="text/javascript">
// Data input taken from "label", not "text" like usual
var lstData = [{id: 0, 'label': 'story'},{id: 1, 'label': 'bug'},{id: 2, 'label': 'task'}];
$("#foo").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.label.localeCompare(term)===0; }).length===0) {
return {id:term, 'label':term};
}
},
data: { results: lstData, text: 'label' }
});
</script>
Library you are using is used to filter options in a select box. It doesn't take new input, as per their own documentation:
Select2 is a jQuery based replacement for select boxes.It supports searching, remote data sets, and infinite scrolling of results.
I would suggest you to use jQueryUI Autocomplete or TypeAhead

Categories

Resources