Select2 AJAX Tags - javascript

I have the following JSON, that is retrieved via /tags:
[
{
"id": "CSS",
"text": "CSS"
},
{
"id": "HTML",
"text": "HTML"
},
{
"id": "JavaScript",
"text": "JavaScript"
},
{
"id": "jQuery",
"text": "jQuery"
},
{
"id": "MySQL",
"text": "MySQL"
},
{
"id": "PHP",
"text": "PHP"
}
]
I have an <input /> that is made to accept tags by using Select2:
<input name="Tags" id="Tags" value="PHP,HTML,jQuery" />
And I have attached Select2 this way:
$("#Tags").select2({
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
multiple: true,
ajax: {
url: '/tags',
dataType: "json",
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {
results: data
};
}
}
});
Problems
When I load the page, the default values go off.
The Select2 fires a request to /tags, but it doesn't load the tags.
There are no errors in the console too. I am using Select2 3.5.2 from CDN. Where am I going wrong?

Well, I used this. Looks like a hack or work-around.
$("#Tags").select2({
tags: true,
multiple: true
});
$.getJSON("/tags", function (data) {
if (data.length > 0)
$("#Tags").select2({
tags: data,
multiple: true
});
});
Hope this helps for someone. I will keep this open till I get better suggestions.

Related

How to use Kendo UI on Multi Select with Search using Post API

I have added Kendo UI on multi-select and use Post API to fetch the data on the basis of the search.
Here is the code in which I have tried to implement it.
var searchx = ""
var ds = new kendo.data.DataSource({
transport: {
read: {
url : "https://searchapi/list",
type: 'POST',
data: function (params) {
console.log("1");
var searchTerm = params.term && params.term != "" ? params.term : searchx;
var query = {
"txt": [
{
"txt: "Level4",
"values": [
"1819"
]
},
{
"txt": "Level3",
"values": []
},
{
"txt": "Level2",
"values": []
},
{
"txt": "Leve1",
"values": [
"278"
]
}
],
"xyz": [
{
"dt": "2022-04-24",
"field": "startDate"
},
{
"dt": "2022-05-24",
"field": "endDate"
}
],
"sorts": [],
"limit": 50,
"q": searchTerm
}
searchx = searchTerm;
console.log("2");
console.log(JSON.stringify(query));
return JSON.stringify(query);
//return Json(ds, JsonRequestBehavior.AllowGet);
},
contentType: 'application/json',
dataType: 'json',
success: function(data){
},
datatype: "json",
beforeSend: function (xhr) {
console.log('beforeSend');
xhr.setRequestHeader('Authorization','Bearer #Session.AuthToken~');
}
}
},
serverFiltering: true,
serverSorting: true,
placeholder: "Select One..."
});
$("#Tasks").kendoMultiSelect({
placeholder: "Select Tasks...",
filter: "contains",
autoBind: false,
dataValueField: "objectId",
dataTextField : "title",
dataSource : ds
});
Autocomplete / Typeahead search . I have created a Multi-select control by using kendo.The Multi-Select is not working Can anybody can help me with this

How to get all ID's of all Checked data in all pages on Datatables

Hi i have my datatables with checkbox at the first column
i able to get the checked checkbox id but i cannot get all the data on the other page
i have this to render my datatables
var tableDelcar;
function LoadTableDelcar() {
tableDelcar = $('#tblDelcar').DataTable({
//dom: 'Brtip',
order: [[1, 'asc']],
buttons: [
'csv', 'excel', 'pdf', 'print'
],
pageLength: 10,
"ajax": {
async: false,
type: 'POST',
contentType: 'application/json',
url: 'MaintenancePage.aspx/getCarDelMaintable',
"dataSrc": "d",
dataType: 'json',
},
"columns": [
{
"d": null,
render: function (data, type, row, meta) {
return '<input type="checkbox" class="select" id="' + row.CAR_NO + '"></td>';
}, title: "Action"
},
{ "data": "CAR_NO", title: "Car No" },
{ "data": "FINDINGS", title: "FINDINGS" },
{ "data": "ActionOwner", title: "Action Owner" },
{ "data": "Auditor", title: "Status" },
{ "data": "COORDINATOR", title: "COORDINATOR" }
]
});
}
and this is my function on getting the ID's of the checked checkboxes
function DeleteCar() {
var IDs = $("#tblDelcar input:checkbox:checked").map(function () {
return $(this).attr("id");
}).get(); alert(IDs);
}
Make sure your DOM is loaded when you call your function in the other page.
you have error ?

jQuery UI autocomplete in AJAX/JSON

I have a problem with jQuery UI autocomplete that I'm trying to resolve with a lot of research and only resolved it partialy. I've managed to make it work at all with this code:
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://wger.de/api/v2/exercise/?format=json",
type: "GET",
data: { name: request.term },
dataType: "json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
}
}));
}
});
}
});
I'm working with open source API in JSON, here is an example:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 436,
"license_author": "Andrew Carothers",
"status": "1",
"description": "<p>1 Minute for each exercise</p>\n<ol>\n<li>Hold feet 6 inches off ground</li>\n<li>Crunches</li>\n<li>Side Crunches (L)</li>\n<li>Side Crunches (R)</li>\n<li>Heel Touches</li>\n<li>Plank Crunch</li>\n<li>Scissor Kicks</li>\n<li>Swim Kicks</li>\n<li>V Crunches</li>\n<li>Hold feet 6 in off ground</li>\n</ol>\n<p>Exercises can be substituted to vary workout</p>",
"name": "10 Min Abs",
"name_original": "10 Min Abs",
"creation_date": "2016-12-09",
"uuid": "3c5f6e1c-cb22-4a9f-a13e-d14afeb29175",
"license": 2,
"category": 10,
"language": 2,
"muscles": [],
"muscles_secondary": [],
"equipment": []
}
]
}
I want to get autocomplete suggestions with letters from "name" in JSON, but instead I've got whole JSON array, even with non-existing objects. I've already tried item.results[0].name, but everything I've got is TypeError: item.results is undefined. How to modify $.ajax to get "name" value of JSON object in autocomplete suggestions?
Thanks for any help.
does this work :
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://wger.de/api/v2/exercise/?format=json",
type: "GET",
data: { name: request.term },
dataType: "json",
success: function(data) {
response($.map(data.results, function(index,item) {
return {
label: item.name,
value: item.name
}
}));
}
});
}
});

Select2 Ajax can't select options being pulled in from API

I'm trying to use the data in my API to populate a select input. I'm using Select2 and have everything working but am unable to select anything once results are found. I'll post my code below, I've been working on this for over 12 hours and can't find anything on the internet that works or even helps to get closer.
HTML:
<select id="school_input"></select>
Select2 Setup:
function formatResults (results) {
if (results.loading) return "Searching...";
var markup = "<div class='select2-result'>" + results.school_name + "</div>";
return markup;
}
$('#school_input').select2({
ajax: {
url: "http://services.url.com/services/globalopponentlookup.ashx",
dataType: 'jsonp',
delay: 250,
data: function (params) {
return {
school_name: params.term,
};
},
processResults: function (data, params) {
return {
results: data.schools,
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
templateResult: formatResults
});
Example of data being pulled in from API:
jQuery31101273177236076506_1487863085363({
"schools": [
{
"school_search_keywords": "florida",
"website": "http://www.cf.edu/",
"school_id": "1514",
"school_name": "Central Florida Community College",
"school_website": "http://www.cf.edu/",
"school_location": "Ocala, FL ",
"school_mascot": "Patriots",
"school_logo_file": "CFpats.png",
"conference_id": "155",
"school_last_updated": "2/26/2014 9:23:51 AM",
"school_zip": "34474",
"school_ncaa_code": "0",
"school_abbrev": null,
"logo": "http://clients.url.com/files/logos/njcaa/CFpats.png",
"colors_id": null,
"url": null,
"safe_text_white": null,
"safe_text_black": null,
"primary_background": null,
"primary_text": null,
"secondary_background": null,
"secondary_text": null,
"client_id": null,
"created": null,
"deleted": null
},
{
"school_search_keywords": "florida",
"website": "http://www.easternflorida.edu/athletics/",
"school_id": "2521",
"school_name": "Eastern Florida State College",
"school_website": "http://www.easternflorida.edu/athletics/",
"school_location": "Cocoa, FL",
"school_mascot": "Titans",
"school_logo_file": "Eastern-Florida-State.png",
"conference_id": "155",
"school_last_updated": "1/19/2016 4:03:58 PM",
"school_zip": "32922",
"school_ncaa_code": null,
"school_abbrev": "EFSC",
"logo": "http://clients.url.com/files/logos/njcaa/Eastern-Florida-State.png",
"colors_id": null,
"url": null,
"safe_text_white": null,
"safe_text_black": null,
"primary_background": null,
"primary_text": null,
"secondary_background": null,
"secondary_text": null,
"client_id": null,
"created": null,
"deleted": null
}
]
You need to have Id value in the JSON in order to make it selectable. https://jsfiddle.net/adiioo7/Lqso63mw/2/
JS
function formatResults (results) {
if (results.loading) return "Searching...";
var markup = "<div class='select2-result'>" + results.school_name + "</div>";
return markup;
}
function formatRepoSelection (results) {
return results.school_name;
}
$('#school_input').select2({
ajax: {
url: "https://api.myjson.com/bins/15d345",
dataType: 'json',
delay: 250,
data: function (params) {
return {
school_name: params.term,
};
},
processResults: function (data, params) {
$(data.schools).each(function(){
this.id=this.school_id;
});
return {
results: data.schools,
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
templateResult: formatResults,
templateSelection: formatRepoSelection
});
You need to return your markup from the formatResults() function :
function formatResults (results) {
if (results.loading) return "Searching...";
return "<div class='select2-result'>" + results.school_name + "</div>";
}
See the documentation

Why typeahead.js is not showing all items in the ajax response?

I am trying to use typeahead.js for showing ajax results in a form.
At first I tried with Bloodhound suggestion engine which comes with typeahead by default. But it wasn't showing all the items (i just shows 1 or sometimes two) returned by the server.
Following is the code I used;
$('.autocomplete').livequery(function () {
var input = this;
$(input).removeClass('autocomplete');
var _source = new Bloodhound({
limit: 25,
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
queryTokenizer: Bloodhound.tokenizers.obj.whitespace('Text'),
prefetch: $(input).attr('data-source'),
remote: {
url: $(input).attr('data-source') + '?query=%QUERY',
wildcard: '%QUERY'
}
});
_source.initialize();
$(input).typeahead({
hint: true,
highlight: true,
minLength: 0
}, {
displayKey: 'Text',
source: _source,
templates: {
notFound: 'No results found'
}
});
$(input).on('typeahead:selected', function (evt, item) {
$(input).parent().parent().find('input[type="hidden"]').val(item.Value);
});
})
Then I tried to do it without Bloodhound using following code without any change in results;
$('.autocomplete').livequery(function () {
var input = this;
$(input).removeClass('autocomplete');
$(input).typeahead({
hint: true,
highlight: true,
limit: 50,
minLength: 0
}, {
displayKey: 'Text',
source: function (query, syncResults, asyncResults) {
$.get($(input).attr('data-source') + '?query=' + query, function (data) {
asyncResults(data);
});
},
templates: {
notFound: 'No results found'
}
});
$(input).on('typeahead:selected', function (evt, item) {
$(input).parent().parent().find('input[type="hidden"]').val(item.Value);
});
})
The response from the Server for the requests is as follows;
[
{
"Text": "Marketing Executive",
"Value": 1
},
{
"Text": "CEO",
"Value": 5
},
{
"Text": "Manager",
"Value": 6
},
{
"Text": "Accountant",
"Value": 7
}]
What is wrong with this? and how can I get typeahead to display all results returned by the Server?
This is a bug in the control. This can be fixed by below code change in typeahead.bundle.js
Switch lines 1723 and 1724 so it looks like this
that._append(query, suggestions.slice(0, that.limit - rendered));
rendered += suggestions.length;
Kudos for the post Bootstrap Typeahead not showing hints as expected

Categories