Select2 Multiple: Add several items with one copy+paste - jquery-select2

I want to add several items in a select2 input field at once.
If I copy+paste "Hawaii Alaska" into the select-multiple example here, then I get:
No results found
In my case spaces are not allowed in the items.
Is there a way to insert N space sperated items via copy+paste?
Desired result: (x)Hawaii (x)Alaska

you can add token separators in your select2 to identify characters as stopping points for your tags/choices, but unfortunately it bugs on the last copy pasted item
//try copy pasting bug,invalid, enhancement, wontfix
//then try bug,invalid, enhancement
//you will see the problem
var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
var placeholder = "select";
$(".mySelect").select2({
tokenSeparators: [',', ', ', ' '],
data: data,
placeholder: placeholder,
allowClear: false,
minimumResultsForSearch: 5
});
here is the codepen
http://codepen.io/anon/pen/dMWQbd
its opened as a bug in github on the library
https://github.com/select2/select2/issues/3458

Related

How to prevent select2 to call select2:close the second time when selectOnClose is set to true?

I am using Select2 V. 4.0.10
I want to have a select2 that behaves the same way when you select using the Enter key and the Tab key.
What happens is that when selecting using the Tab key, the close event is called twice, which is not what was intended to do.
var data = [
{ id: 0, text: 'New' },
{ id: 1, text: 'In Process' },
{ id: 2, text: 'Draft' },
{ id: 3, text: 'Submitted' },
{ id: 4, text: 'Deleted' }
];
$(".test").select2({
allowClear: true,
selectOnClose: true,
data: data,
placeholder: "Select a status"
});
$("select.test", "body").off("select2:close").on("select2:close", function (e){
// This is called twice
console.log("select2:close");
});
select.test {
width: 200px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<select class="test"></select>
Here are the sequences of the select2 events that are triggered when selecting with the Tab/Enter key.
TAB
select2:opening
select2:open
select2:closing
select2:selecting
change
change.select
select2:closing
select2:close
select2:select
select2:close
ENTER
select2:opening
select2:open
select2:selecting
change
change.select
select2:closing
select2:close
select2:select
As the pattern in always the same, the solution was to create a variable that would be toggled on when select2:select was triggered, and use that to see if it was be used before.
Notice, instead of using the global window object you should rather use a class variable or a prototype property to store this boolean.
var data = [
{ id: 0, text: 'enhancement' },
{ id: 1, text: 'bug' },
{ id: 2, text: 'duplicate' },
{ id: 3, text: 'invalid' },
{ id: 4, text: 'wontfix' }
];
window._select2Select = false;
$(document).on('select2:select', "select", function (e) {
window._select2Select = true;
});
$(".test").select2({
allowClear: true,
selectOnClose: true,
data: data,
placeholder: "Select a status"
});
$("select.test", "body")
.off("select2:close")
.on("select2:close", function(e) {
if(window._select2Select){
window._select2Select = false;
return;
}
console.log("select2:close");
window._select2Select = false;
});

Using select2 how can I collapse/expand optgroups?

I'm using select2 (v 4.0.3) with Bootstrap 3 and I have to display several hundreds of alternatives per optgroup. Now I wish to collapse/expand the optgroups on click to make it a bit more manageable. I couldn't find any info on this so I thought I'd post a question.
I found an approach to this problem but I couldn't get it to work (it seems a bit outdated issue #730). The basic problem with that approach now is that in the current version of select2 elements aren't created until they are needed. Also, the class names seem to have changed a bit, as have apparently the names of events in the move to the latest version.
So far I've managed to get the collapse/expand functionality to work for the optgroups, but issues arise when the user provides text input (check the fiddle).
$(function () {
var data = [
{
text: "Group 1",
children: [
{ id: 'A1', text: 'a1'},
{ id: 'B2', text: 'b2'},
{ id: 'C3', text: 'c3'}]
},
{
text: "Group 2",
children: [
{ id: 'A2', text: 'a2'},
{ id: 'B3', text: 'b3'},
{ id: 'C1', text: 'c1'}
]
}];
$('#mySelect')
.select2({data: data, placeholder : 'Select one' });
// Toggle group on click
$('.select2')
.on('click', function(){
$('.select2-results__option').on('click', function(){
$(this).find('.select2-results__options--nested').toggle();
});
});
});
When the text input is used select2 runs the search and the events I've registered are dropped. My plan was to capture text input and check if the input field is empty or not, based on which I can decide to recreate the optgroup listeners or show all optgroups. Any help in this direction would be appreciated.

select2 loading array data example not working

The loading array data example from the official documenation is just not working for me.
https://jsfiddle.net/Jngai1297/v64rwj7b/7/
html
<select class="js-example-data-array-selected">
<option value="2" selected="selected">duplicate</option>
</select
javascript
var hidata = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
$(".js-example-data-array").select2({
data: hidata
})
$(".js-example-data-array-selected").select2({
data: hidata
})
The examples are straight out from the doc and the external resources are correct as well. Been hacking on it half the day and searched around and found nothing.
$(document).ready(function() {
var airPorts = [
{id:0,text:'airport one'},
{id:1,text:'airport two'},
{id:2,text:'airport three'},
{id:3,text:'airport four'},
];
$('.select2').select2({
data: airPorts,
});
});

SELECT2 AJAX not selecting results - Ember.js Ember Cli Custom Component

The AJAX functionality of Select2 4.0.0 doesn't seem to be working. It displays the results from the AJAX however when you click on the a result item it does not select it. I have wasted hours on this any help would be appreciated.
The following code does not work:
var staticdata = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
self._select = self.$().select2({
placeholder: self.get('placeholder'),
tokenSeparators: [','],
multiple: true,
ajax: {
url: "http://localhost:9990/api/v1/users/",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return {
results: staticdata
};
},
cache: true
}
});
However when I try it WITHOUT Ajax it works and the results are selecting into the input field:
var staticdata = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
self._select = self.$().select2({
placeholder: self.get('placeholder'),
tokenSeparators: [','],
multiple: true,
data: staticdata
});
So this issue was due to using select2 as custom ember component.
When you create an ember component you can either select an existing html tag e.g.
1. self.$('#selecttext').select2(...)
Where the html tag is located in your ember cli location templates/components/select2-component.hbs:
<select id="selecttext" class=" form-control input-md select2-hidden-accessible" multiple="" tabindex="-1" aria-hidden="true">
</select>
OR alternatively just initialize the component it self using:
2. self.$().select2(...)
When using approach 2. I am guessing select2 AJAX callback somehow loses the reference to select2 component. So that when you select a result from the list select2:selecting event is not generated and hence the result value is not selected.
I tested this using:
self._select.on("select2:selecting", function(e) {
alert('selecting');
});
However when you use approach 1. ajax callback does NOT lose the reference to the select2 component and generates the "select2:selecting" event and works as expected with the results being able to be selected.
Hence this works:
didInsertElement: function() {
var self = this;
var staticdata = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
self._select = self.$('#selecttext').select2({
// note we are explicitly initialising select2 component on #selecttext
placeholder: self.get('placeholder'),
tokenSeparators: [','],
multiple: true,
tags: false,
//data: staticdata
ajax: {
url: "http://localhost:9990/api/v1/users/",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data, page) {
return {
results: staticdata
};
},
cache: true
}
}); //select2 END
} //didInsertElement END

Select2 Find existing or type new always show first option as blank

I added a select2 and it always show first option as blank.
just below the blank option, it always shows what i type in select2 textfield. Any Idea, how i can fix it.
= hidden_field_tag :tags // present in HAML form
// javascript
$('#tags').select2
createSearchChoice: (term, data) ->
if $(data).filter((->
#text.localeCompare(term) == 0
)).length == 0
return {
id: term
text: term
}
return
multiple: false
data: [
{
id: 0
text: 'story'
}
{
id: 1
text: 'bug'
}
{
id: 2
text: 'task'
}`enter code here`
]
Try this .....
Your input field should be like this
%input#tags{:style => "width: 300px", :type => "hidden"}
Your js code should be like this
$("#tags").select2({
placeholder:"Select an option",
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'
}
]
});
You no longer need to use createSearchChoice if you want to do this with Select2, you can just use the tags option. Right now you shouldn't be seeing the blank option, as you aren't passing one to Select2 at all, so this is lacking a bit of information that would explain that issue.
Select2 will automatically hide blank options though if you have a placeholder set, which I would always recommend. So the hacky solution is to set the placeholder option to whatever you want ("Select a few tags..."), but that only works if this is actually a blank option and not just a CSS issue. You can tell if it's a blank option if Select2 highlights it whenever you start searching, as it will automatically highlight the first option.
It would make more sense for this to be a CSS issue, maybe a bit too much padding somewhere, as the tag (or choice from createSearchChoice) should be inserted automatically at the top of the search results. So even if there was a spare blank option sitting around, it would show under the newly created search choice.

Resources