jquery select2 v4 store new options to data - jquery-select2-4

I am using Select2 and I can create dynamic options using tags: true but when I select a previous option, the newly added option has disappeared.
How can I save it to data so it's always visible?
I've added a jsfiddle but it's not pretty but does demonstrate my problem
var data = [{
id: 0,
text: '<div style="font-size: 1.2em; color:green">enhancement</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
title: 'enchancement'
},
{
id: 1,
text: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>',
title: 'bug'
}];
$("#other").select2({
tags: true,
data: data,
escapeMarkup: function(markup) {
return markup;
},
createTag: function(params) {
var obj = {
id: 'new_' + params.term,
text: '<div style="font-size: 1.2em; color:blue">' + params.term + '</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
title: params.term
};
return obj;
},
insertTag: function (data, tag) {
// Insert the tag at the end of the results
data.push(tag);
}
});

You need to trigger the select2:select function
Try this
$("#other").select2({
tags: true,
data: data,
escapeMarkup: function(markup) {
return markup;
},
createTag: function(params) {
var obj = {
id: 'new_' + params.term,
text: '<div style="font-size: 1.2em; color:blue">' + params.term + '</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
title: params.term,
isNew : true
};
return obj;
}
}).on('select2:select', function (e) {
if(e.params.data.isNew) {
data.push({id: e.params.data.id, text: '<div style="font-size: 1.2em; color:blue">' + e.params.data.text + '</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>', title: e.params.data.text});
}
});

Related

Jquery UI Autocomplete- How to format results AND add button at end?

I've figured out how to change the formatting on my results:
https://github.com/salmanarshad2000/demos/blob/v1.0.4/jquery-ui-autocomplete/custom-html-in-dropdown.html
And I've figured out how I can add a link to the bottom of the results:
Jquery Auto complete append link at the bottom
What I can't figure out is how to do both at the same time.
The closest that I've come is the following:
$( "#search1" ).autocomplete({
source: products,
minLength: 3,
select: function( event, ui ) {
event.preventDefault();
},
focus: function(event, ui) {
event.preventDefault();
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
console.log(ul.content)
var $div = $("<div></div>");
$("<img style='height:76px;'>").attr("src", item.image).appendTo($div);
$("<span></span>").text(item.label).appendTo($div);
($div).append( "<a href='https://google.com'>Click Me</a>" )
return $("<li></li>").append($div).appendTo(ul);
};
The problem is that adds the link to each individual returned result, rather than slamming it onto the end of the list.
I've tried various incarnations of wrapping the link (li, div, etc) but nothing's working.
What do I need to do to get a link as the last thing on the list?
JS Fiddle: http://jsfiddle.net/spgbq6w7/13/
Consider the following code.
Working Example: http://jsfiddle.net/Twisty/wur8vok9/23/
HTML
Search: <input id="search1">
JavaScript
var products = [{
value: "MS-Word",
label: "Microsoft Word 2013",
image: "https://upload.wikimedia.org/wikipedia/commons/4/4f/Microsoft_Word_2013_logo.svg"
},
{
value: "MS-Excel",
label: "Microsoft Excel 2013",
image: "https://upload.wikimedia.org/wikipedia/commons/8/86/Microsoft_Excel_2013_logo.svg"
},
{
value: "MS-Outlook",
label: "Microsoft Outlook 2013",
image: "https://upload.wikimedia.org/wikipedia/commons/0/0b/Microsoft_Outlook_2013_logo.svg"
},
{
value: "MS-PowerPoint",
label: "Microsoft Word 2013",
image: "https://upload.wikimedia.org/wikipedia/commons/b/b0/Microsoft_PowerPoint_2013_logo.svg"
},
{
value: "MS-Access",
label: "Microsoft Access2013",
image: "https://upload.wikimedia.org/wikipedia/commons/3/37/Microsoft_Access_2013_logo.svg"
},
{
value: "Adobe-PSP",
label: "Adobe Photoshop CC",
image: "https://upload.wikimedia.org/wikipedia/commons/a/af/Adobe_Photoshop_CC_icon.svg"
},
{
value: "Adobe-LR",
label: "Adobe Lightroom CC",
image: "https://upload.wikimedia.org/wikipedia/commons/5/56/Adobe_Photoshop_Lightroom_Classic_CC_icon.svg"
},
{
value: "Adobe-PRM",
label: "Adobe Premiere Pro CC",
image: "https://upload.wikimedia.org/wikipedia/commons/5/58/Adobe_Premiere_Pro_CS6_Icon.png"
},
{
value: "Adobe-ACR",
label: "Adobe Acrobat",
image: "https://upload.wikimedia.org/wikipedia/commons/0/0b/Adobe_Acrobat_v8.0_icon.svg"
},
{
value: "Adobe-ILS",
label: "Adobe Illustrator CS6",
image: "https://upload.wikimedia.org/wikipedia/commons/d/d8/Adobe_Illustrator_Icon_CS6.png"
}
];
$(function() {
$("#search1").autocomplete({
source: products,
minLength: 3,
open: function() {
var $li = $("<li>");
var $link = $("<a>", {
href: "#",
class: "see-all"
}).html("See All Results").click(function(e) {
e.preventDefault();
$("#search1").autocomplete("option", "minLength", 0);
$("#search1").autocomplete("search", "");
}).appendTo($li);
$li.appendTo($('.ui-autocomplete'));
},
select: function(event, ui) {
event.preventDefault();
$("#search1").autocomplete("option", "minLength", 3);
},
focus: function(event, ui) {
event.preventDefault();
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
console.log(ul.content)
var $div = $("<div>").css("position", " relative");
$("<img>", {
src: item.image
}).css("height", "38px").appendTo($div);
$("<span>").css({
position: "absolute",
top: 0,
display: "inline-block",
"margin-left": "3px"
}).text(item.label).appendTo($div);
return $("<li>").append($div).appendTo(ul);
};
});
So you're using _renderItem() properly. I removed the Link from here based on the example you linked to. I moved this to the open callback as is shown in the example. I also switched some of your code. It wasn't wrong, I just prefer this method.
So the items get rendered so that the image and label show as desired. The the open call back adds a final link item that causes the a search for all items. See more: http://api.jqueryui.com/autocomplete/#method-search
Can be called with an empty string and minLength: 0 to display all items.
When an item is selected, the preferred minLength is returned to ensure that if the user starts a new search, it operates the same way it did the first time.
Update
http://jsfiddle.net/Twisty/wur8vok9/40/
Minor cleanup and better separation of code and style.
Hope this helps.

JqGrid searchoptions with select2 existing value

I'm trying to integrate select2 for JqGrid filter form. I'm using JqGrid min 4.6 & Select2 min 4.0.1. The filter works fine but I'm unable to retrieve the value that has been set through select2 once the filter form is closed and reopened. i.e. dataInit e1 does not return the existing value of the select input. I must be doing something wrong?
JqGrid Column Model:
{
name: 'CurrencyID', hidden: true, search: true, stype: 'select', searchtype: 'number', searchoptions: {
searchhidden: true,
sopt: ['eq', 'ne'],
dataInit: function (el) {
intiGridFilterSelecr2Field(el, paramFromView.CurrencyOptions);
}
},
searchrules: { required: true }
},
Parameters:
#section scripts{
<script>
var paramFromView = {
CurrencyOptions: {
searchURL: '#Url.Action("GetCurrency", "Controller")',
detailURL: '#Url.Action("CurrencyDetailsJson", "Controller")',
idField: 'CurrencyID',
txtField: 'Description'
}
};
</script>
}
Select2 Helper:
function intiGridFilterSelecr2Field(element, options) {
var comboPageSize = 15;
var quietMillis = 200;
var placeHolderText = 'Choose...'
var defaults = {
searchURL: '',
detailURL: '',
idField: '',
txtField: ''
};
var options = $.extend({}, defaults, options);
var select2Element = $(element);
select2Element.select2({
width: 'element',
minimumInputLength: 1,
placeholder: placeHolderText,
ajax: {
url: options.searchURL,
dataType: 'json',
quietMillis: quietMillis,
cache: false,
data: function (params) {
return {
name: params.term,
page: params.page,
pageSize: comboPageSize
};
},
processResults: function (data) {
var more = (data.page * comboPageSize) < data.total;
var resultsArr = [];
for (var i = 0; i < data.result.length; i++) {
resultsArr.push({ id: data.result[i][options.idField], text: data.result[i][options.txtField] });
}
return { results: resultsArr, more: more };
}
},
}).each(function (index, element) {
var idCombo = $(this);
// The problem is that idCombo.val() is always empty.
// element:select2-hidden-accessible
if (idCombo.val() != null && idCombo.val().length > 0) {
$.ajax(options.detailURL, {
data: {
id: idCombo.val()
},
dataType: 'json',
cache: false
}).done(function (data) {
var optselected = select2Element.find('option').filter(function () { return this.value == data[idField] && this.text == data[txtField] && this.selected })
if (optselected == undefined || optselected.length == 0) {
var $optionContact = $("<option selected></option>").val(data[idField].toString()).text(data[txtField]);
var toBeRemoved = select2Element.find('option').filter(function () { return this.value == data[idField] });
if (toBeRemoved != undefined) {
toBeRemoved.remove();
}
select2Element.append($optionContact).trigger('change.select2');
}
});
}
});
}
When the filter is being set...
When Loading the existing filter. How do I pass this CurrencyID = 1 to select2 helper?
Update:
With Oleg's answer, I updated my code as below.
{
name: 'CurrencyID', hidden: true, searchtype: 'number', search: true,
stype: "select", searchoptions: {
searchhidden: true,
sopt: ["eq", "ne"],
dataUrl: paramFromView.CurrencyOptions.searchURL,
buildSelect: function (data) {
var obj = jQuery.parseJSON(data);
var i, options = [];
for (i = 0; i < obj.result.length; i++) {
options.push("<option value='" + obj.result[i][paramFromView.CurrencyOptions.idField] + "'>" +
obj.result[i][paramFromView.CurrencyOptions.txtField] + "</option>");
}
return "<select>" + options.join("") + "</select>";
},
noFilterText: "Any",
selectFilled: function (options) {
setTimeout(function () {
$(options.elem).select2({
width: 'element',
});
}, 0);
}
},
searchrules: { required: true }
},
I'm almost there with what I wanted to achieve. However I'm still facing some difficulties.
When the filter is initially loaded, value is selected on the dropdown but query value is empty. i.e. if the user clicks on the find button soon after the filter form is loaded, no filter will be set.
I still cannot get select2 styles working.
I can demonstrate how to use select2 with free jqGrid fork of jqGrid, which I develop. I get the demo from the README of the old version 4.14.1 (the current released version is 4.15.3) and modified it to demonstrate the usage of select2.
The main part of the code could be
stype: "select",
searchoptions: {
sopt: ["eq", "ne"],
...
selectFilled: function (options) {
setTimeout(function () {
$(options.elem).select2({
width: "100%"
});
}, 0);
}
}
See https://jsfiddle.net/Lae6kee7/2/. You can try to choose an option in the filter toolbar in "Shipped via" column and the open the search dialog. You will see that the select2 will have the same option selected.
If you would load the data via Ajax request posted by select2 than your code will be much more complex as it could be. It's important to understand that such way is really required only for really large set of possible value. I means the number of items larger as 100000 items for example. On the other side, the most use cases required less as 1000 options. In the case it would be more effective to load all the data as options of select and then convert the select to select2. select2, which uses local select works much more quickly from the users point of view.
The code will be easier in my opinion if you will use dataUrl instead of ajax option of select2. You can use dataUrl to return from the server all different values, which can be used in select2 and to use buildSelect to build <select> from JSON data returned from the server. The demo https://jsfiddle.net/Lae6kee7/23/ demonstrates that. I made the demo for JSFiddle, which supports Echo service (see here), which allows to simulate server responses. Your real code should contains mostly only dataUrl, buildSelect and the code of selectFilled, which I included above.
Additionally, I'd recommend you to consider to use <datalist> (see here for example), which could be good alternative to select2. All modern web browsers contains native support of <datalist> and thus <datalist> works very quickly. Try to search in the first Client column of my demos. You will see control, which will be very close to select2. Additional advantage of <datalist>: one will be able not search for only exact predefined values like test10, test11 or test12, but for substrings like 1. Compare
with
or
with

select2 set initial value with ajax load, and custom template

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

noData messsage not auto wrapping on window resize

When displaying a long noData message on High Chart, the text is not wrapping and is going out of screen/chart.
DEMO: http://jsfiddle.net/9xLyo7xj/
lang:{noData:'this is a really long sentence that is supposed to wrap around the window but somehow it is not - I would like it to wrap for easier reading'}
HTML
<button id="add">Add data</button>
<button id="remove">Remove data</button>
<button id="showCustom">Show custom message manually</button>
JS
$(function() {
var chart,
btnRemove = $('#remove'),
btnAdd = $('#add'),
btnShow = $('#showCustom');
btnAdd.click(function() {
chart.series[0].addPoint(Math.floor(Math.random() * 10 + 1)); // Return random integer between 1 and 10.
});
btnRemove.click(function() {
if (chart.series[0].points[0]) {
chart.series[0].points[0].remove();
}
});
btnShow.click(function() {
if (!chart.hasData()) {
chart.hideNoData();
chart.showNoData("Your custom error message");
}
});
$('#container').highcharts({
title: {
text: 'No data in line chart - with custom options'
},
series: [{
type: 'line',
name: 'Random data',
data: []
}],
lang: {
noData: "this is a really long sentence that is supposed to wrap around the window but somehow it is not - I would like it to wrap for easier reading"
},
noData: {
style: {
fontWeight: 'bold',
fontSize: '15px',
color: '#303030',
width: 400px
}
}
});
chart = $('#container').highcharts();
});

Unable to show "Searching" when using select2 (Loading remote data)

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.

Resources