select2 programmatically without knowing results in advance - javascript

I am trying to write a test for a Javascript select2 control and I would like to automatically select the first item. Since it's using ajax I do not know what the first item is. All the examples I have seen create <option> however they assume knowledge of the value. How can I select the first item without knowledge? (Note this example only runs the ajax command after 3 items are entered).
var $selector = $("#foo");
$selector.show().select2({
allowClear: true,
placeholder: "--------",
minimumInputLength: 3,
ajax: {
url: "...",
type: 'GET',
dataType: 'json',
delay: 250,
data: function(term, page) {
return {
number__icontains: term
};
},
results: function(data) {
return {
results: $.map(data.objects, function(option) {
return {
'id': option.id,
'text': option.desc
};
})
};
},
cache: false
},
initSelection: function(element, callback) {
...
}
});

Related

How can I fill all data in select2 (4.0) when page loaded?

I am using select2 plugin (v.4.0).
What I am trying to do:
$("#search-input-chains").select2({
placeholder: "Unit",
theme: "bootstrap4",
allowClear: true,
initSelection: function (element, callback) {
callback({id: 1, text: 'Text'});
},
ajax: {
url: function () {
return getURLForFilial();
},
dataType: 'json',
delay: 250,
processResults: function (response) {
console.log(response);
return {
results: response
};
},
cache: false
}
});
function getURLForFilial() {
return '/user/rest/data/entry/units/branches?type=1';
}
I need to understand, whether my control has data retrieved from DB or not, and if there is no data - this select list shall not be activated.
I found how I can understand the data amount:
$("#search-input-chains").data().select2.results.$results[0].childNodes.length
(maybe there is another way that is much better?)
But this piece of code returns 0 until I will activate (click) on the select2 box and trigger AJAX request to find data.
I read a lot about how can I perform the pre-call off AJAX, but it doesn't work.
I tried to trigger event on select2 in such a way:
$("#search-input-chains").val().trigger('change');
Please, advice, how can I load data to my select2 control with the page load to understand whether I need to disable this select or not?
I've made it via AJAX:
ajax({
type: 'GET',
url: '/user/rest/data/entry/units/branches?type=1'
}).then(function (data) {
if (data.length !== 0) {
chainsSelectElement.prop("disabled", false);
chainSelectorHasData = true;
} else {
// create the option and append to Select2
let option = new Option('Nothing', 'null', true, true);
chainsSelectElement.append(option);
chainSelectorHasData = false;
chainsSelectElement.prop("disabled", true);
}
getDataForSubdivisions();
});

Select2: Creating tags with ajax

I am using the select2 library.
My select2 element can search the database for each tag via the ajax and that works fine.
My issue is, I want the user to also be able to create a new tag. Looking at their documentation I should use the createTag option; however, this fires as soon as I click into the element and on each key press.
Can anyone offer any guidance on how I can achieve my goal?
here is my code thus far
I am using ajax top search for tags but I would also like to create new tags to the database. I have tried doing this via createTag but this seems to be firing as soon as I click in the HTML element and on each key press.
Here is my code:
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
cache: true,
},
createTag: function(params) {
alert('tag created') // This is were I would put my ajax POST.
}
});
After reading the documentation again, I can see I should have been using the events https://select2.org/programmatic-control/events
I used the createTag option to assign newTag: true to newly created tags and used the select2:selected event which checked if a new tag had been selected and, if it was, sent an ajax request to the server to create that tag.
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
minimumInputLength: 3,
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
// cache: true,
},
createTag: function(params) {
let term = $.trim(params.term);
if (term.length < 3)
{
return null
}
return {
id: term,
text: term,
newTag: true,
}
},
});
$('.tags').on('select2:select', function (e) {
let tag = e.params.data;
if (tag.newTag === true)
{
axios.post('/api/newtag', {
name: tag.text,
type: 'default',
})
}
});

Forcing select2 ajax call

I have 2 select2 and when one of them changes the other one loads it's content using the built in select2 ajax function, the problem is that in the case only one element comes from the server I want it to be loaded by default, but for what I have seen the ajax call is only executed when opening the select2 in question. Here is the code I run when the first selec2 is changed in order to change the second's data:
$select1.on('change', function () {
initializeLocationsSelect2($select2, $select1.val(), $template, omId);
});
function initializeLocationsSelect2(tag, s1Value, template, id) {
tag.val("");
tag.select2({
placeholder: "Please Select One",
minimumInputLength: 0,
multiple: true,
tokenSeparators: [","],
tags: false,
ajax: {
url: tag.data('url'),
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
id: id,
value: s1Value
};
},
results: function (data, page) {
return {
results: data
};
}
},
formatSelection: function (item) {
return $.format(template.html(), item.text);
},
formatResult: function (item) {
return $.format(template.html(), item.text);
},
escapeMarkup: function (m) { return m; }
});
}
just in case it is relevant, the second select2 is attached to a <hidden> tag

Set selected value on select2 without loosing ajax

I have this select2 code in my html (mvc with razor) page:
$('#QuickSearchState').select2({
minimumInputLength: 3,
width: 'resolve',
ajax: {
url: '#Url.Action("QuickSearchState", "DataCenter")',
contentType: 'application/json',
dataType: 'json',
type: 'POST',
traditional: true,
quietMillis: 400,
data: function(term, page) {
var data = {
term: term
};
return data;
},
results: function(data, page) {
return { results: data };
}
},
initSelection: function(element, callback) {
var data = { id: element.val(), text: element.val() };
callback(data);
},
formatResult: function(format) {
return format.label;
},
formatSelection: function(format) {
//this is a knockout view model
vmNewAddress.IdState(format.id);
vmNewAddress.StateName(format.stateName);
return format.label;
},
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) { return m; }
});
But i have another select in my code that can set a state in this select, but i dont know how to set this value to that select.
In my html i have this:
<select class="width-xl" data-bind="options: vm.GivenLocationsForConnection, optionsText: 'DisplayFormat', value: SelectedLocation"></select> -> first select that can fill the second state search select with a state
#Html.Hidden("query", null, new { #id = "QuickSearchState", #class = "width-xl", placeholder = "Ej. Montevideo" }) -> second select, this is a search for states and selects a single state
I am not sure if this is what you want but if you only want to select a value in the select you can just do below
$("#QuickSearchState").select2("val", "<YOUR VALUE>");

$tree.tree is not a function

I am generating a tree in plone using an add-on product called collective.virtualtreecategories . However, I keep getting a weird javascript error and the tree cannot be displayed.
On my browser's error console, I get the following:
$tree.tree is not a function
Here is the part of code that produces the error:
$tree.tree({
data: {
type: "json",
url: "##vtc-categories-tree.json",
async: false
},
lang: {
new_node: "New category"
},
rules: {
deletable: ["folder"],
renameable: ["folder"],
draggable: "none",
droppable: "none",
},
callback: {
beforechange: function(node, tree_obj) {
return before_change_node()
},
onselect: function(node, tree_obj) {
node_selected(node)
},
oncreate: function(node) {
jq(node).attr('rel', 'folder')
},
onrename: function(node, lang, tree_obj, rb) {
old_id = node.id // may be undefined (new node)
new_name = jq(node).children("a:visible").text();
// shared code. Server determines if creating/renaming by the old_name value
jq.ajax({
type: 'POST',
url: "vtc-category-added-renamed",
data: {
'category_path': selected_category(node),
'old_id': old_id,
'new_name': new_name
},
success: function(data) {
jq.jGrowl(data.msg, {
life: 1500
});
// set/change node id
if (data.result) {
node.id = data.new_id
}
},
dataType: 'json',
traditional: true
})
},
beforedelete: function(node, tree_obj) {
jq.ajax({
type: 'POST',
url: "vtc-category-removed",
data: {
'category_path': selected_category(node)
},
success: function(data) {
jq.jGrowl(data.msg, {
life: 3000
});
},
dataType: 'json',
traditional: true
});
return true;
}
}
});​
The complete code listing can be found HERE
Can someone help me fix this?
UPDATE:
I should perhaps add that, this was working before in a different setting. Now, I just recreated the project and thats when I got this error.
As far as I can tell from your code $tree isn't a function, its an element
on line 89 var $tree = jq('ul#VTCTree');
therefore I assume .tree() is a JQuery widget and isn't working as expected?
Just seen some of the comments and the updates. Have you checked the path/file inclusion of the tree plugin/widget?
On my browser's error console, I get the following:
if your browser is Internet Explorer, the extra comma that you have here
droppable: "none",
is a widely known problem.
Not a problem for Firefox, but will give unexpected results, like 3 elements in the following array. but length = 4
myArr = [1,2,3,,]
also, check this https://stackoverflow.com/a/5139232/982924
I had the same issue, even though I had jquery loaded and the jquery.filetree.min plugin loaded. I was missing the jquery UI js which is also required.

Categories

Resources