Can not select any item from Select2 - javascript

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";
}
});

Related

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/

Load row information from DataTable created with AJAX

I have the next form.
This table is created with an AJAX call, here is the code:
$.ajax({
type: 'POST',
url: urlServer + "../webserviceURL", //URL del Web Service
data: '{"us":"' + sessionStorage.Usuario + '"}',
dataType: 'json',
contentType: 'application/json',
timeout: 600000,
error: function (xhr) {
lineas += '<tr><th colspan="8" class="text-center">No se encontraron registros de los cursos.</th></tr>';
$('#Tabla6').html(lineas);
bootbox.alert("No se pudo cargar los cursos.");
},
success: function (data) {
$('#Tabla6').dataTable({
"aaData": JSON.parse(data.d),
"aoColumns": [{
"mDataProp": "Id"
}, {
"mDataProp": "Nombre"
}, {
"mDataProp": "Contraseña"
}, {
"mDataProp": "Tipo"
}, {
"mDataProp": "Correo"
}, {
"mData": "",
"bSortable": false,
"mRender": function (oObj) {
return '<span class="btn btn-success fa fa-edit"></span>';
}
}]
});
}
});
Works fine but I want to load the row information when user click the "pencil button" and I dont know exactly how to do this. The only thing I need is load the row information to this method:
$('#Tabla6').on('click', '.glyphicon-edit', function () {
var id = $(this).attr('data-id');
editarDatosUsu(id);
});
editarDatosUsu Method:
function editarDatosUsu(id) {
if ($('#U' + id).length) {
var id = $('#U' + id).attr('data-id');
$('#IdUs').val(id);
var rev = $('#U' + id + '-1').html();
var pass = $('#U' + id + '-2').html();
var tipo = $('#U' + id + '-3').html();
var mail = $('#U' + id + '-4').html();
$('#user').val(rev);
$('#pass').val(pass);
$('#tipo').val(tipo);
$('#mail').val(mail);
}
Here's what I do:
$("#dashboardTable").on( 'click', '.approveLink', function () {
var tableRow = table.row( $(this).parents('tr') );
var row = $(this).parents('tr');
approveDashboard(tableRow.data().id, row);
} );
(where table is the datatable)

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

Unable to select items populated via jsonp in select2

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/

jqgrid addrowdata after calling ajax

I have question regarding adding another rowdata at the end of my jqgrid. What I wanted to do is that everytime I do a simple search on a particular transaction, and display it on my jqgrid, i want to have another row at the end which have my total computations. Below is my complete jqgrid code:.
$("#tblSupplier").jqGrid({
url: '',
datatype: 'local',
jsonReader : {
root: function(obj) {
var root = [];
if ('error' in obj)
{
showMessage(obj.error['class'] + ' error: ' + obj['error']['msg']);
}
else
{
var totalBdFt = '';
var bdft=0;
var amt=0;
var totalAmount = '';
$.each(obj['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = obj['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
if (fldName == 'transaction_date'){
$('#tallyDate').val(rowArrayValue);
}
if (fldName == 'supplier_name'){
$('#supplierName').val(rowArrayValue);
}
if (fldName == 'board_foot'){
bdft = parseFloat(bdft) + parseFloat(rowArrayValue);
}
if (fldName == 'total_amount'){
amt = parseFloat(amt) + parseFloat(rowArrayValue);
}
});
root[rowIndex] = row;
$('#totalBdft').val(parseFloat(bdft));
$('#totalAmt').val(parseFloat(amt));
});
};
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("SessionID"),
'dataType': 'data',
'simple_search_value':trim($("#searchSupAny").val()),
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Transaction Num', 'Wood Classification', 'Specie', 'Total Board Foot', 'Price', 'Total Amount'],
colModel:[
{name:'transaction_num'},
{name:'wood_classification_desc'},
{name:'wood_specie_desc'},
{name:'board_foot'},
{name:'price'},
{name:'total_amount'}
],
viewrecords: true,
sortname: 'transaction_num',
sortorder: 'desc',
loadonce:false,
height:'100%',
caption: "sample summary"
});
var newRowData = [{ "wood_classification_desc": 'total should b here', "wood_specie-desc": "total bdft here", "total_amount": "total amount here"}];
$("#tblSupplier").addRowData('transaction_num',newRowData);
})
my newRowData displays only on load, but after I do a simple search, it will also gone. But my jqgrid with ajax data working good. So how should I do it to maintain my additional row everytime I call ajax?

Categories

Resources