Select2 - avoiding duplicates tags - javascript

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"); });

Related

i dont want select2 multi select drop down loose data in page refresh. select2 drop down should maintain state

I don't want select2 multi select drop down loose data in page refresh. select2 drop down should maintain state
below is my code. its working fine, I have only problem that select2 is losing selection/data if we refresh the page.My requirement is even after page refresh it should not remove there values/or empty.
$processOrderNbr.select2({
ajax: getProcessOrderNbr(),
minimumInputLength: 4,
placeholder: " ",
allowClear: false,
multiple: true
});
function getProcessOrderNbr() {
return {
url: 'GetProcessOrder',
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchKeyword: params
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item,
id: item
}
})
};
}
};
}
You need to put them again into the select2 boxes.
I had a similar issue, where I work with window.sessionStorage to store the selected values. After reloading the page, I set the values stored in the session storage into the select2 boxes with this code:
var selectionList = [{ id: window.sessionStorage.getItem("searchValue"), text: window.sessionStorage.getItem("searchValue")}];
$("#searchValue").select2({
data: selectionList
});
$('#searchValue').val(window.sessionStorage.getItem("searchValue")).trigger("change");
To store the values in the window.sessionStorage you can use this code:
$('#searchValue').select2({
...
.on("change", function (e) {
window.sessionStorage.setItem("searchValue", $(this).val());
}
...
Maybe this solution helps you in your case, but someone knows a better solution?
If you need to show the previous wrote value after reloading the page without losing the data that is the solution.
var dataCategory = JSON.parse(sessionStorage.getItem('category'));
var select = $("#category");
select.select2({
tags: true,
allowClear: true,
maximumInputLength: 30,
maximumSelectionLength: 20,
tokenSeparators: [',', ' '],
data: dataCategory
}).on("change", function (e) {
var selected = []; // create an array to hold all currently wrote by user
// loop through each option
$('#category option').each(function() {
// if it's selected, add it to the array above
if (this.selected) {
selected.push(this.value);
}
});
// store the array of selected options
sessionStorage.setItem('category', JSON.stringify(selected));
});
// set and show the previous wrote keywords
var dataCategoryLength = dataCategory.length;
for (var i =0; i < dataCategoryLength; i++) {
$('#category').val(dataCategory).trigger('change');
}

Dynamic search bar - Adding element from drop down in ASP.NET MVC5

I'm programming in ASP.NET MVC5. On one of my views I need to be able to create a search bar. For this example, lets say you are searching for names. When you start typing a person's name, all of the results will be displayed in a drop down list as you type.
Here is the tricky part that I need help with. I want there to be a button for each entry in the drop down list to "Add" that person name to a table.
For example, I'm looking for the name "Debo" As I type "D-E-B", I see the name I want in the drop down list. I click "Add" and it removes the name "Debo" from the drop down list and adds it to my table. Once "Debo" has been added to the table, I need to be able to see Debo's age and gender that I wouldn't see in the drop down list.
I don't have any code examples because I'm not even sure where to start. I've researched this like crazy, but I cannot find anything. Any help or pointing me in the right direction, will be greatly appreciated,
I am using autocomplete by JQueryUI.
Please refer below code hopefully it will helps you.
JavaScript Code:
$("#member_CompanyName").autocomplete({
highlightClass: "bold-text",
search: function () {
$(this).addClass('working');
},
source: function (request, response) {
var companyDetails = new Array();
$.ajax({
url: "/ControllerName/JsonActionResult",
async: false,
data: {
"parm": request.term
},
success: function (data) {
if (data.length === 0) {
companyDetails[0] = {
label: "No Result Found",
Id: ""
};
} else {
for (var i = 0; i < data.length; i++) {
companyDetails[i] = {
label: data[i].Value,
Id: data[i].Key
};
$("#no-companyfound").css("display", "none");
}
}
}
});
response(companyDetails);
},
minLength: 2,
select: function (event, ui) {
/*Select Function works on when you selects element from Response List*/
$.ajax({
async: false,
url: "/ControllerName/JsonActionResultonClick",
data: {
"id": ui.item.Id
},
success: function (data) {
// Do your success logic here
},
error: function (xhr, ajaxOptions, thrownError) {
// Error Logic here
}
});
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
Controller Code:
[HttpGet]
public JsonResult JsonActionResult(string parm) {
// Replace your special Character like "-,~" etc from your search string
var result = new List < KeyValuePair < string,
string >> ();
foreach(var item in _obj_fulldetails.GetCompanylistSearch(parm)) {
result.Add(new KeyValuePair < string, string > (item.Value.ToString(), item.Text));
}
return Json(result, JsonRequestBehavior.AllowGet);
}
You can implement "Add"
button your logic on Item select. If you still want add button you can edit response string into JS.
See my response screenshot :

Select2: Update option after selecting new tag

I implemented a tagging system where you can choose from existing tags or add new tags. After a new tag has been selected it will persisted using an AJAX call.
For achieving this I use the callback createTag and the event select2:select. Because I like to create the tag only when it is selected I do an AJAX call for this if the event select2:select gets triggered.
The problem is that I need to update the already created option of select2 with the ID I get from persisting my new tag to the database. What's the cleanest solution for this?
Here's what I have:
$('select.tags').select2({
tags: true,
ajax: {
url: '{{ path('tag_auto_complete') }}',
processResults: function (data) {
return {
results: data.items,
pagination: {
more: false
}
};
}
},
createTag: function (tag) {
return {
id: tag.term, // <-- this one should get exchanged after persisting the new tag
text: tag.term,
tag: true
};
}
}).on('select2:select', function (evt) {
if(evt.params.data.tag == false) {
return;
}
$.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
// ----> Here I need to update the option created in "createTag" with the ID
option_to_update.value = data.id;
}, "json");
});
My problem was that I did not add the new tag as an <option> tag to the native select field.
This is necessary because select2 checks for the values set trough select2.val(values) if an <option> tag with this value does exist. If not select2 silently throws the value out of the array and sets the array of values which have a corresponding option tag in the underlying select field.
So this is how it works correct now (for select2 4.0.x):
$('select.tags').select2({
tags: true,
ajax: {
url: '{{ path('tag_auto_complete') }}',
processResults: function (data) {
return {
results: data.items,
pagination: {
more: false
}
};
}
},
createTag: function (tag) {
return {
id: tag.term,
text: tag.term,
tag: true
};
}
}).on('select2:select', function (evt) {
if(evt.params.data.tag == false) {
return;
}
var select2Element = $(this);
$.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
// Add HTML option to select field
$('<option value="' + data.id + '">' + data.text + '</option>').appendTo(select2Element);
// Replace the tag name in the current selection with the new persisted ID
var selection = select2Element.val();
var index = selection.indexOf(data.text);
if (index !== -1) {
selection[index] = data.id.toString();
}
select2Element.val(selection).trigger('change');
}, 'json');
});
The minimal AJAX response (JSON format) has to look like this:
[
{'id': '1', 'text': 'foo'},
{'id': '2', 'text': 'bar'},
{'id': '3', 'text': 'baz'}
]
You may add additional data to each result for let's say own rendering of the result list with additional data in it.
Just to update:
The new syntax is
e.params.args.data.id
not
e.params.data.id

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);
}

Select2 limit number of tags

Is there a way to limit the number of tags a user can add to an input field using Select2?
I have:
$('#tags').select2({
containerCssClass: 'supplierTags',
placeholder: "Usual suppliers...",
minimumInputLength: 2,
multiple: true,
tokenSeparators: [",", " "],
placeholder: 'Usual suppliers...',
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.name.localeCompare(term) === 0;
}).length === 0) {
return {id: 0, name: term};
}
},
id: function(e) {
return e.id + ":" + e.name;
},
ajax: {
url: ROOT + 'Call',
dataType: 'json',
type: 'POST',
data: function(term, page) {
return {
call: 'Helpers->tagsHelper',
q: term
};
},
results: function(data, page) {
return {
results: data.tags
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
name: item[1]
});
});
callback(data);
}
});
It would be great if there could be/is a simple parameter like limit: 5 and a callback to fire when the limit is reached.
Sure, with maximumSelectionLength like so:
$("#tags").select2({
maximumSelectionLength: 3
});
Maximum Selection Length
Select2 allows the developer to limit the number of items that can be
selected in a multi-select control.
http://ivaynberg.github.io/select2/
It has no native callback, but you can pass a function to formatSelectionTooBig like this:
$(function () {
$("#tags").select2({
maximumSelectionLength: 3,
formatSelectionTooBig: function (limit) {
// Callback
return 'Too many selected items';
}
});
});
http://jsfiddle.net/U98V7/
Or you could extend formatSelectionTooBig like this:
$(function () {
$.extend($.fn.select2.defaults, {
formatSelectionTooBig: function (limit) {
// Callback
return 'Too many selected items';
}
});
$("#tags").select2({
maximumSelectionLength: 3
});
});
Edit
Replaced maximumSelectionSize with the updated maximumSelectionLength. Thanks #DrewKennedy!
method 1
$("#tags").select2({
maximumSelectionLength: 3
});
method 2
<select data-maximum-selection-length="3" ></select>
list of all available options https://select2.org/configuration/options-api
The accepted answer doesn't mention that the maximumSelectionLength statement should be inside the document.ready function. So for anyone who is having the same trouble I did, here is the code that worked for me.
$(document).ready(function() {
$("#id").select2({
maximumSelectionLength: 3
});
});
$("#keywords").select2({
tags : true,
width :'100%',
tokenSeparators: [','],
maximumSelectionLength: 5,
matcher : function(term,res){
return false;
},
"language": {
'noResults': function(){
return "Type keywords separated by commas";
}
}
}).on("change",function(e){
if($(this).val().length>5){
$(this).val($(this).val().slice(0,5));
}
});
Try like this. It'll short up to 5 keywords.
This is not working for me, I am getting query function not defined for Select2, so here is another workaround.
var onlyOne=false;
$("selector").select2({
maximumSelectionSize:function(){
if(onlyOne==true)
return 1;
else
return 5;
}
});
This setting can be defined as function and it's called every time you start searching something.
Important thing is that you have something defined outside this select2 closure so you can check it (access it). In this case you could somewhere in your program change value of onlyOne and of course this returned limit can also be dynamical.
This is working for me.
$("#category_ids").select2({ maximumSelectionLength: 3 });
Send the Get Request to action method and the Map the class properties to drop down id and text property
$("#DropDownId").select2({
minimumInputLength: 3,
maximumSelectionLength: 10,
tags: [],
ajax: {
url: "#Url.Action("ActionName", "ControllerName")",
type: "get",
dataType: 'json',
delay: 250,
data: function (params) {
return {
Title: params.term // search term
};
},
processResults: function (response) {
return {
results: $.map(response, function (item) {
return {
text: item.Title,
id: item.Id
}
})
};
}
}
});
Action Method
[HttpGet]
public JsonResult ActionName(string Title)
{
ClassName obj= new ClassName ();
obj.Title = "PMPAK";
obj.Id= -1;
obj.Add(nibafInstitute);
return Json(obj, JsonRequestBehavior.AllowGet);
}
public class ClassName
{
public int Id{ get; set; }
public string Title { get; set; }
}

Categories

Resources