Select2 - missing text on tags (in template) - jquery-select2

Following this example:
https://select2.org/data-sources/ajax
Select2 v4.0.13
how do i style the missing text to show up?
// -- - --- - -SELECT2 ------------------
// https://select2.org/data-sources/ajax
function select2CommonSearch(selector, url, placeholder){
$(selector).select2({
ajax: {
url: url,
dataType: 'json',
delay: 200,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function (data) {
return {
results: data,
}
},
},
placeholder: placeholder,
allowClear: true,
// minimumInputLength: 1,
templateResult: select2formatSearchResults,
templateSelection: select2formatSearchResultsSelection
});
}
function select2formatSearchResults (repo) {
if (repo.loading) {
return repo.text;
}
var $container = $(
"<div class='select2-result-repository clearfix'>" +
// "<div class='select2-result-repository__avatar'><img src='" + repo.first_name + "' /></div>" +
// "<div class='select2-result-repository__meta'>" + repo.name +
"<div class='select2-result-repository__title'>"+ repo.name +"</div>" +
// "<div class='select2-result-repository__description'></div>" +
// "<div class='select2-result-repository__statistics'>" +
// "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> </div>" +
// "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> </div>" +
// "<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> </div>" +
// "</div>" +
"</div>" +
"</div>"
);
$container.find(".select2-result-repository__title").text(repo.first_name);
// $container.find(".select2-result-repository__description").text(repo.first_name);
// $container.find(".select2-result-repository__forks").append(repo.first_name + " Forks");
// $container.find(".select2-result-repository__stargazers").append(repo.first_name + " Stars");
// $container.find(".select2-result-repository__watchers").append(repo.first_name + " Watchers");
return $container;
}
function select2formatSearchResultsSelection (repo) {
return repo.text;
}
It works fine for regular items.

Related

set value to select2 dropdown which retrieved from database in ASP.NET MVC

<script type="text/javascript">
$(document).ready(function () {
//following values i retrived from database and i want to display into select2 dropdown
var selectedValue1 = '43,48,47,57';
$('#ddlCity1').select2({
minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: true,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
dataType: 'json',
delay: 250,
url: '#Url.Action("GetCityList", "DemoMVC")',
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.City
});
});
return { results: newData };
},
cache: true
},
});
$(".city1").on("select2:select", function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
$('.city1').on('select2:unselect', function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
});
//Dropdown with select2 control
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>City</label>
<select id="ddlCity1" class="city1" style="width:500px"></select>
</div>
</div>
</div>
i assume that this action "GetCityList" returned json
$('#ddlCity1').select2({ minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: true,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%"
});
function ("/DemoMVC/GetCityList", {}, "json", success, falier) {
$.ajax({
url: url,
data: paramters,
contentType: "application/json; charset=utf-8",
dataType: returnFormat,
success: function (data) {
success(data);
let htmlData = "<option value='' selected disabled hidden>Select City...</option>";
for (let i = 0; i < Object.values(data)[1].length; i++) {
htmlData = htmlData + Template(Object.values(data)[1][i]);
}
$("#ddlCity1").html(htmlData);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText + ': ' + xhr.responseText + ': ';
console.log('Error - ' + errorMessage);
},
type: 'GET',
});
}
function Template(item) {
let itemHtml = "<option value='" + item.id + "'>" + item.city + "</option>";
return itemHtml;
}

Tooltip C3JS - Add a row in the table

I'm trying to add a footer on the table displayed in the tooltip. Inside this row I would like to show a particular data loaded from a json file.
Chart:
<script>
var scene;
$.getJSON('assets/json/chartc3.json', function (data) {
scene = data;
var chart = c3.generate({
bindto: '#chartc3',
data:
{
json: scene,
keys:
{
x: 'round',
value: ['Marketable', 'Total Requested Capacity', 'Your Bid'],
},
types: {
Marketable: 'area'
},
colors: {
Marketable: '#A09FA2',
'Total Requested Capacity': '#272E80',
'Your Bid': '#8EBF60'
}
},
axis:
{
x: {
tick:
{
culling:
{
max: 10
}
},
type: 'category'
},
y:
{
min: 0,
padding: {
bottom: 0
},
tick:
{
values: [[0], [d3.max(d3.values(scene))]],
format: function (d) { return d3.format(',f')(d) + ' kWh/h' }
//or format: function (d) { return '$' + d; }
}
}
},
tooltip: {
contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
var $$ = this, config = $$.config, CLASS = $$.CLASS,
titleFormat = config.tooltip_format_title || defaultTitleFormat,
nameFormat = config.tooltip_format_name || function (name) { return name; },
valueFormat = config.tooltip_format_value || defaultValueFormat,
text, i, title, value, name, bgcolor;
// You can access all of data like this:
for (i = 0; i < d.length; i++) {
if (!(d[i] && (d[i].value || d[i].value === 0))) { continue; }
// ADD
if (d[i].name === 'data2') { continue; }
if (!text) {
title = 'MY TOOLTIP'
text = "<table class='" + CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
}
name = nameFormat(d[i].name);
value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
text += "<tr class='" + CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "; border-radius: 5px;'></span>" + name + "</td>";
text += "<td class='value'>" + value + "</td>";
text += "</tr>";
}
**var surchargedata;
$.getJSON('assets/json/surcharge.json', function(data)
{
console.log("Prima"+text);
surchargedata=data;
text += "<tr class='" + CLASS.tooltipName + "-Surcharge" + "'>";
text += "<td class='name'>" + surchargedata[i].Surcharge+ "</td>";
text += "<td class='value'>" + surchargedata[i].Surcharge+ "</td>";
text += "</tr></table>";
console.log(text);
})**
return text;
}
}
});
});
</script>
I printed the log and the table seems generated well but if you have a look at the tooltip :
I can't see the last row.
Here the log for the table generated:
<table class='c3-tooltip'>
<tr>
<th colspan='2'>MY TOOLTIP</th>
</tr>
<tr class='c3-tooltip-name-Marketable'>
<td class='name'><span style='background-color:#A09FA2; border-radius: 5px;'>
</span>Marketable
</td>
<td class='value'>5,220,593 kWh/h</td>
</tr>
<tr class='c3-tooltip-name-Total Requested Capacity'>
<td class='name'><span style='background-color:#272E80; border-radius: 5px;'>
</span>Total Requested Capacity
</td>
<td class='value'>16,449,051 kWh/h</td>
</tr>
<tr class='c3-tooltip-name-Your Bid'>
<td class='name'>
<span style='background-color:#8EBF60; border-radius: 5px;'>
</span>Your Bid
</td>
<td class='value'>100,000 kWh/h
</td>
</tr>
<tr class='c3-tooltip-name-Surcharge'>
<td class='name'>50.38</td>
<td class='value'>50.38</td>
</tr>
</table>
You are loading the surcharge data using $.getJSON when you generate your tooltip. And your surcharge line is added to the text that you are generating for the tooltip in the callback. By this time, the actual tooltip function has returned with whatever text was generated before the $.getJSON call.
The easiest way to fix this would be to load your surcharge data first by moving your surcharge $.getJSON to wrap around your original script.
Here is the updated script.
<script>
var surchargedata;
$.getJSON('assets/json/surcharge.json', function (data) {
surchargedata = data;
var scene;
$.getJSON('assets/json/chartc3.json', function (data) {
scene = data;
var chart = c3.generate({
bindto: '#chartc3',
data:
{
json: scene,
keys:
{
x: 'round',
value: ['Marketable', 'Total Requested Capacity', 'Your Bid'],
},
types: {
Marketable: 'area'
},
colors: {
Marketable: '#A09FA2',
'Total Requested Capacity': '#272E80',
'Your Bid': '#8EBF60'
}
},
axis:
{
x: {
tick:
{
culling:
{
max: 10
}
},
type: 'category'
},
y:
{
min: 0,
padding: {
bottom: 0
},
tick:
{
values: [[0], [d3.max(d3.values(scene))]],
format: function (d) { return d3.format(',f')(d) + ' kWh/h' }
//or format: function (d) { return '$' + d; }
}
}
},
tooltip: {
contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
var $$ = this, config = $$.config, CLASS = $$.CLASS,
titleFormat = config.tooltip_format_title || defaultTitleFormat,
nameFormat = config.tooltip_format_name || function (name) { return name; },
valueFormat = config.tooltip_format_value || defaultValueFormat,
text, i, title, value, name, bgcolor;
console.log(JSON.stringify(d))
// You can access all of data like this:
for (i = 0; i < d.length; i++) {
if (!(d[i] && (d[i].value || d[i].value === 0))) { continue; }
// ADD
if (d[i].name === 'data2') { continue; }
if (!text) {
title = 'MY TOOLTIP'
text = "<table class='" + CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
}
name = nameFormat(d[i].name);
value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
text += "<tr class='" + CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "; border-radius: 5px;'></span>" + name + "</td>";
text += "<td class='value'>" + value + "</td>";
text += "</tr>";
}
console.log("Prima" + text);
text += "<tr class='" + CLASS.tooltipName + "-Surcharge" + "'>";
text += "<td class='name'>" + surchargedata[i].Surcharge + "</td>";
text += "<td class='value'>" + surchargedata[i].Surcharge + "</td>";
text += "</tr></table>";
console.log(text);
return text;
}
}
});
});
})
</script>

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.

JQuery-UI dialog widget and Fine-Uploader Upload

I have this problem when I am trying to make an upload. The url configured in the request endpoint for the FineUploader instance is not reached.
I am using FineUploader v3.7.1 and JQuery-UI v1.10.3.
Below is my code:
SCRIPT
$(document).ready(function () {
$(function () {
$('#dialog').dialog({
autoOpen: false,
width: 400,
height: 500,
resizable: false,
modal: true,
draggable: false,
buttons: [
{
text: "Aceptar",
click: function () {
$(this).dialog("close");
}
}
]
});
});
$('#upload').fineUploader({
text: {
uploadButton: 'Agregar imágen al evento',
deleteButton: 'Eliminar imagen'
},
// template for one item in file list
fileTemplate:
'<span>' +
'<div class="qq-progress-bar"></div>' +
'<span class="qq-upload-spinner"></span>' +
'<span class="qq-upload-finished"></span>' +
'<span class="qq-upload-file"></span>' +
'<span class="qq-upload-size"></span>' +
'<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
'<a class="qq-upload-retry" href="#">{retryButtonText}</a>' +
'<a class="qq-upload-delete" href="#">{deleteButtonText}</a>' +
'<span class="qq-upload-status-text">{statusText}</span>' +
'</span>',
classes: {
},
request: {
endpoint: '<%= Url.Action("UploadNewDesign", "Account") %>'
},
deleteFile: {
enabled: true,
endpoint: '<%= Url.Action("DeleteNewDesign", "Account") %>',
method: 'POST'
},
multiple: true,
validation: {
},
showMessage: function (message) {
},
messages: {
}
})
.on('submit', function (event, id, name) {
})
.on('submitted', function (event, id, name) {
var fileItemContainer = $(this).fineUploader('getItemByFileId', id);
$('#dialog').html(fileItemContainer);
$("#dialog").dialog("open");
})
.on('complete', function (event, id, fileName, responseJSON) {
if (responseJSON.success) {
}
})
.on('submitDelete', function (event, id) {
})
.on('deleteComplete', function (event, id, xhrOrXdr, isError) {
if (!isError) {
}
});
})
HTML
<div id="upload"></div>
<div id="dialog"></div>
This only happens when I put the fileTemplate html (Calling the FineUploader API) on a JQuery Dialog Widget. If I try to put the fileTemplate html in an element inside the view, the Action Controller is reached.
UPDATE
Below if my Updated code, I was duplicating the DOM of the fileTemplate
SCRIPT
$('#upload').fineUploader({
text: {
uploadButton: 'Agregar imágen al evento',
deleteButton: 'Eliminar imagen'
},
listElement: $('#dialog')[0],
fileTemplate:
'<span>' +
'<div class="qq-progress-bar"></div>' +
'<span class="qq-upload-spinner"></span>' +
'<span class="qq-upload-finished"></span>' +
'<span class="qq-upload-file"></span>' +
'<span class="qq-upload-size"></span>' +
'<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
'<a class="qq-upload-retry" href="#">{retryButtonText}</a>' +
'<a class="qq-upload-delete" href="#">{deleteButtonText}</a>' +
'<span class="qq-upload-status-text">{statusText}</span>' +
'</span>',
classes: {
},
request: {
endpoint: '<%= Url.Action("UploadNewDesign", "Account") %>'
},
deleteFile: {
enabled: true,
endpoint: '<%= Url.Action("DeleteNewDesign", "Account") %>',
method: 'POST'
},
validation: {
allowedExtensions: ['png'],
sizeLimit: 411062 // 50 kB = 50 * 1024 bytes
},
multiple: true,
showMessage: function (message) {
$('#dialog').html(message);
$("#dialog").dialog("open");
},
messages: {
}
})
.on('submit', function (event, id, name) {
})
.on('submitted', function (event, id, name) {
var fileItemContainer = $(this).fineUploader('getItemByFileId', id);
$('#dialog').html(fileItemContainer);
$("#dialog").dialog("open");
})
.on('complete', function (event, id, fileName, responseJSON) {
if (responseJSON.success) {
var fileName = $(this).fineUploader('getName', id);
$('#tblFiles > tbody:last').append('<tr><td>' + fileName + '</td></tr>');
}
})
.on('submitDelete', function (event, id) {
})
.on('deleteComplete', function (event, id, xhrOrXdr, isError) {
if (!isError) {
}
});
})
HTML
<div id="upload"></div>
<div id="dialog"></div>
<table id="tblFiles">
<tbody></tbody>
</table>
UPDATE
I successfully do what I am trying to do. Please take a look and tell me if it is a better way of doing what I do. Below there are some images (OHH STACKOVERFLOW doesn´t allow me because I don´t have enough reputation, I ended deleting all of it), explaining what I was searching
Finally the code Updated, please let me know if it is a better way
$('#FileTemplate').dialog({
//dialogClass: "no-dialog-titlebar-close",
autoOpen: false,
width: 400,
height: "auto",
resizable: false,
modal: true,
draggable: false,
buttons: [
{
text: "Aceptar",
click: function () {
$(this).dialog("close");
}
}
]
});
$(".ui-dialog-titlebar").hide();
$('#Messages').dialog({
autoOpen: false,
width: "auto",
height: "auto",
resizable: false,
modal: true,
draggable: false,
buttons: [
{
text: "Aceptar",
click: function () {
$(this).dialog("close");
}
}
]
});
$('#Upload').fineUploader({
messages: {
typeError: "{file} tiene una extension inválida. Las extensiones validas son: {extensions}.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
noFilesError: "No files to upload.",
tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.",
retryFailTooManyItems: "Retry failed - you have reached your file limit.",
onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
},
text: {
uploadButton: 'Agregar imágen al evento',
deleteButton: 'Eliminar imagen',
cancelButton: 'Cancel',
retryButton: 'Retry',
failUpload: 'Upload failed',
formatProgress: "{percent}% de {total_size}",
waitingForResponse: "Procesando..."
},
template: '<div class="qq-uploader">' +
'<div class="qq-upload-drop-area"><span>{dragZoneText}</span></div>' +
'<div class="div-button-style"><div>{uploadButtonText}</div></div>' +
'<span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' +
'</div>',
listElement: $("#FileTemplate"),
fileTemplate:
'<span>' +
'<div class="qq-progress-bar"></div>' +
'<span class="qq-upload-spinner"></span>' +
'<span class="qq-upload-finished"></span>' +
'<span class="qq-upload-file"></span>' +
'<span class="qq-upload-size"></span>' +
'<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
'<a class="qq-upload-retry" href="#">{retryButtonText}</a>' +
'<a class="qq-upload-delete-hide" href="#">{deleteButtonText}</a>' +
'<span class="qq-upload-status-text">{statusText}</span>' +
'</span>',
classes: {
deleteButton: "qq-upload-delete-hide",
button: "div-button-style"
},
request: {
endpoint: '<%= Url.Action("UploadNewDesign", "Account") %>'
},
deleteFile: {
enabled: true,
endpoint: '<%= Url.Action("DeleteNewDesign", "Account") %>',
method: 'POST'
},
validation: {
allowedExtensions: ['png'],
sizeLimit: 411062 // 50 kB = 50 * 1024 bytes
},
multiple: true,
showMessage: function (message) {
$('#Messages').html(message);
$("#Messages").dialog("open");
}
})
.on('submitted', function (event, id, name) {
var files = $('#Upload').fineUploader('getUploads');
// SPECIALLY IN THIS PART, WHERE I'M HIDING ALL THE OTHERS FILETEMPLATES
$.each(files, function (index, value) {
var exists = $('#Upload').fineUploader('doesExist', value.id);
if (exists && value.id != id)
$('#Upload').fineUploader('getItemByFileId', value.id).hide();
});
$("#FileTemplate").dialog("open");
})
.on('complete', function (event, id, fileName, responseJSON) {
if (responseJSON.success) {
var fileName = $(this).fineUploader('getName', id);
$('#tblFiles > tbody:last').append(
'<tr>' +
'<td class="hide-element"><input type="hidden" value="' + responseJSON.filename + '"/></td>' +
'<td class="hide-element"><input type="hidden" value="' + id + '"/></td>' +
'<td>' +
'<div class="pointer-cursor" title="Eliminar imagen" onclick="DeleteImage(' + id + ')">' +
'<image src="/Images/trash.png" />' +
'</div>' +
'</td>' +
'<td onclick="SelectImage(' + id + ')" class="pointer-cursor">' + fileName + '</td>' +
'</tr>');
SelectImage(id);
return;
}
$('#Messages').html("Se produjo un error al subir el archivo");
$("#Messages").dialog("open");
})
.on('submitDelete', function (event, id) {
$(this).fineUploader('setDeleteFileParams', { filename: $(this).fineUploader('getName', id)}, id);
})
.on('deleteComplete', function (event, id, xhrOrXdr, isError) {
if (!isError) {
var trIndex;
var trRemoved = false;
var firstFileId;
for (trIndex = 0; trIndex < $('#tblFiles tbody tr').length && !trRemoved; trIndex++) {
var fileId = $($('#tblFiles tbody tr')[trIndex]).find('td input')[1].value;
if (!firstFileId)
firstFileId = fileId;
// Remove the tr associated with file
if (fileId == id) {
$($('#tblFiles tbody tr')[trIndex]).remove();
trRemoved = true;
}
}
if ($('#tblFiles tbody tr').length == 0) {
// No images left
$("#imgUploaded").attr("src", "/Images/no_image_mid.png");
$("#IdImageSelected").val("");
}
else {
// If the image was the selected, selected another
if ($("#IdImageSelected").val() == id)
SelectImage(firstFileId);
}
return;
}
$('#Messages').html("Se produjo un error al querer eliminar el archivo");
$("#Messages").dialog("open");
});
})
function DeleteImage(id) {
$('#Upload').fineUploader('deleteFile', id);
}
function SelectImage(id) {
$('#tblFiles tbody tr').each(function () {
var fileId = $(this).find('td input')[1].value;
// FileName on server
var fileName = $(this).find('td input')[0].value;
var row = $(this).children();
if (fileId == id) {
// Assign the selected style
row.addClass("image-selected");
$("#imgUploaded").attr("src", "<%: _imagesDirectory %>/" + fileName);
$("#IdImageSelected").val(id);
}
else {
row.removeClass("image-selected");
}
});
}
HTML
<table>
<tbody>
<tr>
<td>
<img id="imgUploaded" src="/Images/no_image_mid.png" style="width:200px; height:200px" />
<input type="hidden" class="hide-element" id="IdImageSelected"/>
</td>
</tr>
<tr>
<td>
<div id="Upload"></div>
</td>
</tr>
</tbody>
</table>
<div id="FileTemplate"></div>
<div id="Messages" title="Error"></div>
<table id="tblFiles">
<tbody></tbody>
</table>
I hope you understand what I am trying to do
I'm still a little confused by your code. I'll do my best to answer your question, but it would be make it much easier for me to help you if you would simply provide a link to a page that contains a working version of the code you have listed in your question.
Fine Uploader will create the file items inside of your #dialog, since you have set #dialog as your listElement. This seems like what you want to do, based on your comments. But, you are replacing the entire contents of #dialog every time a file is submitted in your submitted handler. Why? I'm guessing you really don't want to do this. You should take another look at the documentation for jQuery's html function.
You are also overwriting the contents (again) of this same #dialog with messages from Fine Uploader in your showMessage implementation. Again, I'm sure you also don't want to do this. If you want to display these messages in a custom dialog, fine, but you should choose a NEW dialog, not the same one holding the HTML for the uploader.
All I can suggest is that you should remove your submitted handler and your showMessage implementations, as the code you have added to these two sections doesn't make any sense.
Also, you have a bunch of empty options. I'm not sure if you don't understand how those work, if you just have left out portions of your code for some reason.
Finally, you can pass in the jQuery object for your #dialog, since you are using the Fine Uploader jQuery wrapper. Your listElement option can have a value of $('dialog').

No result appear in the autocomplete

The action return a JSonResult and the content is correct. I missed something in the autocomplete code ?
HTML :
<input type="text" class="span12" id="mytextbox" />
The javascript :
<script>
$(document).ready(function () {
$("#mytextbox").autocomplete({
minLength: 2,
source: function(request,response) {
$.ajax({
url: "MyController/MyAction",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { firstname: item.FirstName, lastname: item.LastName, code: item.Code };
}))
}
})
},
messages: {
noResults: "", results: ""
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.firstname + "<br>" + item.lastname + "</a>")
.appendTo(ul);
};
})
</script>
The next code works, where availableTags replace your ajax.
<script>
$(document).ready(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC"];
$("#mytextbox").autocomplete({
minLength: 2,
source: availableTags,
messages: {
noResults: "", results: ""
}
}).data("ui-autocomplete").renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.firstname + "<br>" + item.lastname + "</a>")
.appendTo(ul);
};
});
</script>
This might be helpful: http://api.jquery.com/jQuery.data/#jQuery-data-element
Update:
The problem is this line:
.data("ui-autocomplete").renderItem = function (ul, item) {
you got
.data("ui-autocomplete").**_**renderItem = function (ul, item) {

Resources