Unable to select items populated via jsonp in select2 - javascript

I'm trying to populate a select2 element using geonames data. I have a formatSelection method defined but it will not fire when an item is selected.
Here's the HTML element:
<input id="location" size="30" type="text">​
Select2 binding with format functions:
function locationFormatResult(location) {
var markup = "<table class='location-result'><tr>";
if (location.countryCode !== undefined) {
markup += "<td class='flag-image'><img src='http://www.geonames.org/flags/x/" + location.countryCode.toLowerCase() + ".gif' /></td>";
}
markup += "<td class='location-info'>";
markup += "<div class='location-name'>" + location.name + ", " + location.adminName1 + ", " + location.countryName + "</div>";
markup += "</td></tr></table>";
return markup;
}
function locationFormatSelection(location) {
return location.name + ", " + location.adminName1 + ", " + location.countryName;
}
$(function () {
$('#location').select2({
placeholder: 'Location',
allowClear: true,
width: '260px',
minimumInputLength: 2,
ajax: {
url: 'http://ws.geonames.org/searchJSON',
dataType: 'jsonp',
data: function (term) {
return {
featureClass: 'P',
q: term
};
},
results: function (data) {
return {
results: data.geonames
};
}
},
formatResult: locationFormatResult,
formatSelection: locationFormatSelection,
dropdownCssClass: "bigdrop"
});
});
You can see the full fiddle here: http://jsfiddle.net/6CVbw/1/
Why is selecting an item not working?

I figured it out. When you instantiate the select2 plugin on an element you have to specify an ID attribute. This worked:
$(function () {
$('#location').select2({
id: function(e) { return e.name + '|' + e.adminName1 + '|' + e.countryName },
placeholder: 'Location',
allowClear: true,
width: '260px',
minimumInputLength: 2,
ajax: {
url: 'http://ws.geonames.org/searchJSON',
dataType: 'jsonp',
data: function (term) {
return {
featureClass: 'P',
q: term
};
},
results: function (data) {
return {
results: data.geonames
};
}
},
formatResult: locationFormatResult,
formatSelection: locationFormatSelection,
dropdownCssClass: "bigdrop"
});
});
You can see the updated fiddle here: http://jsfiddle.net/6CVbw/2/

Related

jqGrid filterToolbar only works with some columns

When I try searching for the string Test in the column "Erstellt Von", I get no results. There's no error in the console either.
This is the codepart I used:
var colUserTemplate = {
width: 160, align: 'left',
formatter: function (cellvalue, options, rowObject) {
return "Test";
}
}
In another column, the filtering works perfectly fine:
Here's how grids are loaded and the filterToolbar:
function loadGrid(listname, query, divname, colnames, colmdodel, showFilter, showExcelExport) {
$("#" + divname).jqGrid({
datatype: function () { loadGridData(listname, query, divname); },
colNames: colnames,
colModel: colmdodel,
height: "100%",
loadonce: true,
rowNum: 9999,
gridComplete: function () {
$("#" + divname + "no").html(" [" + $("#" + divname).jqGrid('getGridParam', 'records') + "]");
$("#" + divname).jqGrid('setGridParam', { datatype: 'local' });
},
ondblClickRow: function (rowid, iRow, iCol, e) {
onDoubleClickGrid(rowid, iRow, iCol, e, divname, listname);
}
});
if (showFilter) {
$("#" + divname).jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
}
}
I tried using
if (showFilter) {
$("#" + divname).jqGrid('filterToolbar', {
autosearch: true,
stringResult: true,
searchOnEnter: true,
defaultSearch: "cn", ignoreCase: true
});
}
but it didn't change anything.
If you want to have a look, here's the full code.
Been trying to fix this issue for hours, so any help is appreciated!
EDIT:
When writing this:
var thegrid = $("#" + divname)[0];
console.log("data.d.results: " + data.d.results);
thegrid.addJSONData(data.d.results); //Binding data to the grid
console.log("thegrid:" + thegrid.innerHTML);
I get the following result:
Here's the expanded object:
You use a function to load the data:
function loadGridData(listname, query, divname) {
$.ajax({
url: "/tools/AKG/_api/web/lists/getbytitle('" + listname + "')/Items?" + query,
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data, textStatus, xhr) {
var thegrid = $("#" + divname)[0];
thegrid.addJSONData(data.d.results); //Binding data to the grid
},
error: function (xhr, textStatus, errorThrown) {
alert("error:" + JSON.stringify(xhr));
$('#' + divname + 'records').html(" [0]");
}
});
}
In the success function data.d.results contain your grid data. Before to put this data in addJSONData loop over that column and change its value or better do it at server if possible

Select2 is showing "No result found" message when selecting second time

I am using Select2 with ajax option and its a multiple selection box. I am able to select the record first time. But after selecting first one if i try to select the next one it is not working.
fiddle link for complete code
$('#select2_ajax_complex_id').select2({
tags: true,
maximumSelectionSize: 10,
minimumResultsForSearch: Infinity,
multiple: true,
minimumInputLength: 1,
placeholder: "Search Employee",
//data:o,
id: function(i) {
return i;
},
initSelection: function(element, callback) {
},
ajax: {
type: 'post',
url: "/echo/json/",
allowClear: true,
dataType: 'json',
delay: 250,
params: {
contentType: "application/json"
},
data: function(term, page) {
//Code for dummy ajax response
return {
json: complex_employee_response,
delay: 0
};
},
results: function(data, page) {
return {
results: data
};
},
cache: false
},
formatResult: function(i) {
return '<div>' + i.name + '(' + i.role + ')' + '</div>';
}, // Formats results in drop down
formatSelection: function(i) {
return '<div>' + i.name + '(' + i.role + ')' + '</div>';
}, //Formats result that is selected
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function(m) {
return m;
} // we do not want to escape markup since we are displaying html in results
})
Can some one have a look and help to resolve this?
Remove below block from your code
//data:o,
id: function(i) {
return i;
},
initSelection: function(element, callback) {
},
By using this code ,your problem will fixed
I have created one demo for the same[Edited in your example]
Just refer this URL
https://jsfiddle.net/7m2nv5yw/

ASPNETZERO - How to change index page to render tiles instead of table

I currently have a normal ASPNETZERO index page, which renders a datatable grid with search fuctions. I want to change this view to render "tiles" for each row in the grid. I already have the CSS/HTML for rendering tiles working. I basically want to repurpose the below index.js code to render my tiles, instead of the datatable grid.
(function () {
$(function () {
var _$companyTable = $('#companyTable');
var _companyService = abp.services.app.company;
var _permissions = {
create: abp.auth.hasPermission('Pages.Tenant.Administration.Company.Create'),
edit: abp.auth.hasPermission('Pages.Tenant.Administration.Company.Edit'),
impersonation: abp.auth.hasPermission('Pages.Tenants.Impersonation'),
};
var _createModal = new app.ModalManager({
viewUrl: abp.appPath + 'Nursing/Company/CreateModal',
scriptUrl: abp.appPath + 'view-resources/Areas/Nursing/Views/Company/_CreateModal.js',
modalClass: 'CreateCompanyModal'
});
var _editModal = new app.ModalManager({
viewUrl: abp.appPath + 'Nursing/Company/EditModal',
scriptUrl: abp.appPath + 'view-resources/Areas/Nursing/Views/Company/_EditModal.js',
modalClass: 'EditCompanyModal'
});
var dataTable = _$companyTable.DataTable({
paging: true,
serverSide: true,
processing: true,
responsive: true,
listAction: {
ajaxFunction: _companyService.getCompanies,
inputFilter: function () {
return {
filter: $('#CompanyTableFilter').val()
};
}
},
columnDefs: [
{
targets: 0,
data: null,
orderable: false,
autoWidth: true,
defaultContent: '',
rowAction: {
cssClass: 'btn btn-xs btn-primary blue',
text: '<i class="fa fa-cog"></i> ' + app.localize('Actions') + ' <span class="caret"></span>',
items: [{
text: app.localize('Edit'),
visible: function () {
return _permissions.edit;
},
action: function (data) {
_editModal.open({ id: data.record.id });
}
}]
}
},
{
targets: 1,
orderable: true,
autoWidth: true,
data: "companyName"
},
{
targets: 2,
orderable: true,
autoWidth: true,
data: "companyLegalName"
},
{
targets: 3,
autoWidth: true,
data: "companyTaxID"
},
{
targets: 4,
orderable: true,
autoWidth: true,
data: "currency"
}
]
});
function getCompanies() {
dataTable.ajax.reload();
}
$('#CreateNewCompanyButton').click(function (e) {
_createModal.open();
});
$('#GetCompaniesButton').click(function (e) {
e.preventDefault();
getCompanies();
});
abp.event.on('app.editCompanyModalSaved', function () {
getCompanies(true);
});
abp.event.on('app.createCompanyModalSaved', function () {
getCompanies(true);
});
$('#CompanyTableFilter').focus();
});
How can I change the JS code above to render my tiles instead of the datatable? I also want to retain the search function for the tiles. The app service method GetCompanies used in the JS code above works for rendering my tiles. So that API call will remain the same.
Here is the output I want to achieve from the above JS code.
Here is the current standard ABP index page view. I want to replace this with above tiles.
I figured out a solution. I changed the index.js code by adding the method shown below. I'm using an AJAX call to the API method and then using the results to render my tiled output. This is working for me.
If anyone sees any issues with this approach, please do let me know.
function getCompanies() {
$.ajax({
type: 'GET',
url: '/api/services/app/Company/GetCompanies',
dataType: 'json',
success: function (companies) {
var _tileHtml = "";
//Iterate thru JSON list of values
$.each(companies.result.items, function (i, company) {
//Tile content start
_tileHtml = "<div class='SingleTileContent inline-block'>";
//Header
_tileHtml += "<div class='Tile-header'>";
_tileHtml += "<div class='pull-left inline-block'>";
_tileHtml += "<div class='badge badge-info'>" + company.id + "</div>";
_tileHtml += "</div>";
_tileHtml += "<div class='pull-left inline-block text-bold'> | " + company.companyName + "</div>";
_tileHtml += "</div>";
//Body start
_tileHtml += "<div class='Tile-body text-left'>";
//Body row
_tileHtml += "<div class='Tile-body-detail'>";
_tileHtml += "<label>Legal Name</label> " + company.companyLegalName + "</div>";
//Body row
_tileHtml += "<div class='Tile-body-detail'>";
_tileHtml += "<label>Tax Id</label> " + company.companyTaxID + "</div>";
//Body end
_tileHtml += "</div>";
//Buttons (footer)
_tileHtml += "<div class='Tile-buttons'>";
_tileHtml += "<a href='javascript:;' class='btn btn-xs blue btnEdit' id='EditCompanyButton'>Edit<i class='fa fa-edit'></i></a>";
_tileHtml += "</div>";
//Tile content end
_tileHtml += "</div>";
$("#TestJS2").append(_tileHtml);
});
Count = 0;
},
error: function (ex) {
abp.notify.error('Failed to retrieve companies' + ex);
}
});
}

Using an external auto complete plugin (jQuery) and i am trying to put my own value in json it was not working

This is the continuation with my previous question posted here I am new to the JSON and ajax trying to put my own value in this link the data as per my requirement.
$("document").ready(function() {
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function(index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function(index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function(ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function(index, column) {
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
return result;
}
});
//from here I am customizing the code*/
$("document").ready(function (){
$("#scl_name").mcautocomplete({
// These next two options are what this plugin adds to the autocomplete widget.
showHeader: true,
showHeader: true,
columns: [{
name: 'description',
width: '150px'
}, {
name: 'schoolname',
width: '120px'
}],
// Event handler for when a list item is selected.
/*select: function (event, ui) {
this.value = (ui.item ? ui.item.name : '');
$('#school_Name').text(ui.item ? 'Selected: ' + ui.item.name +this.value);
return false;
},*/
// The rest of the options are for configuring the ajax webservice call.
minLength: 1,
source: function (request, response) {
$.ajax({
url: 'dummy.json',
dataType: 'json',
data: {
featureClass: 'P',
style: 'full',
maxRows: 12,
name_startsWith: request.term,
username: "demo"
},
// The success event handler will display "No match found" if no items are returned.
success: function (data) {
var result;
if (!data || data.length === 0 || !data.schoolname || data.schoolname.length === 0) {
result = [{
label: 'No match found.'
}];
} else {
result = data.schoolname;
console.log(result);
}
response(result);
}
});
}
});
});
with the current one i am getting the output as [object] Now I am not getting any error but i am not getting any value as well :(
This is my html
<input type="text" id="scl_name" class="ipt_Field"/>
Thanks in advance

Can not select any item from Select2

I'm using Select2 with customFormatResult as this code show:
function productFormatResult(product) {
var markup = '<div class="row-fluid">' +
'<div class="col-xs-2"><img src="' + product.url + '" /></div>' +
'<div class="col-xs-10">' + product.value + '</div>' +
'</div>';
var prueba = '<img style="height: 40px;width: 40px;" src="' +
product.url + '" class="img-rounded" id="ProductoForm_0_image" /> ' + product.value;
return prueba;
}
function productFormatSelection(product) {
return product.value;
}
$("input.typeahead").select2({
placeholder: "Buscar producto",
minimumInputLength: 0,
ajax: {
url: Routing.generate('get_products'),
dataType: 'json',
quietMillis: 250,
data: function(term, page) {
return {
filter: term,
page: page
};
},
results: function(data, page) {
var more = (page * 30) < data.total_count;
return {results: data.items, more: more};
}
},
formatResult: productFormatResult,
formatSelection: productFormatSelection,
escapeMarkup: function(m) {
return m;
},
formatNoResults: function() {
return "No se encontraron productos para la palabra actual";
},
formatAjaxError: function() {
return "No hay conexión con el servidor";
}
});
But I can choose/select any item from select when they are showed, why? What's wrong in my code? You can test live example here (look for this text OFERTAS REALIZADAS A FACTURAR: where says Producto)
You need return id.
$("input.typeahead").select2({
id: function(prod) { return prod.value; },
placeholder: "Buscar producto",
minimumInputLength: 0,
id: function(prod){ return "prod"; },
ajax: {
url: Routing.generate('get_products'),
dataType: 'json',
quietMillis: 250,
data: function(term, page) {
return {
filter: term,
page: page
};
},
results: function(data, page) {
var more = (page * 30) < data.total_count;
return {results: data.items, more: more};
}
},
formatResult: productFormatResult,
formatSelection: productFormatSelection,
escapeMarkup: function(m) {
return m;
},
formatNoResults: function() {
return "No se encontraron productos para la palabra actual";
},
formatAjaxError: function() {
return "No hay conexión con el servidor";
}
});

Categories

Resources