JQuery-UI dialog widget and Fine-Uploader Upload - jquery-ui

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').

Related

select2+ASP.NET+MVC set values back to dropdown in edit mode

i am using select2 plugin with ASP.NET+MVC with multiple select option. i am able to save values into database of selected item. now I want to show those values (basically text which associate with those saved ids) into dropdown which has select2 plugin in edit mode.
how can i do that. below is my code.
$(document).ready(function () {
/* below values want to set to dropdown list
var selectedValue1 = '43,48,47,57';
$('#ddlCity1').select2({
multiple: true,
placeholder: "Select City",
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
},
formatResult: function (element) {
return element.text + ' (' + element.id + ')';
},
formatSelection: function (element) {
return element.text + ' (' + element.id + ')';
},
escapeMarkup: function (m) {
return m;
},
});
$(".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>

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

Send Jquery UI Dialog value to Url.Action

Not sure how to pass along a bool to my (working) C# method DeleteTestuser. I've Googled the heck out of this but mileage varies with all kinds of pitfalls, i.e. old information, bad syntax.
Rather than passing confirm as false, below, I need to return a bool if the user confirms the action. Thanks...
index.cshtml
<a href="#Url.Action("DeleteTestUser", "Home",
new {id = testUser.TestUserId, confirm = false})"
id="confirm-delete">
_layout.cshtml
<script type="text/javascript">
$(function () {
$('#dialog-modal').dialog(
{
title: 'Test User',
draggable: false,
resizeable: false,
closeOnEscape: true,
modal: true,
autoOpen: false,
buttons: {
'Yes': function () {
$(this).dialog('close');
confirmResult(true);
},
'No': function () {
$(this).dialog('close');
confirmResult(false);
}
}
});
$('#confirm-delete').click(function () {
$('#dialog-modal').dialog("open");
});
function confirmResult(result) { return result }
});
</script>
Basically, you're recreating your own confirm() with jQuery UI Dialog. I did this and here is a similar case: confirm form submit with jquery UI
Apply this to your scenario and you have something like:
$(function() {
function ui_confirm(message, callback) {
var dfd = $.Deferred();
var dialog = $("<div>", {
id: "confirm"
})
.html(message)
.appendTo($("body"))
.data("selection", false)
.dialog({
autoOpen: false,
resizable: false,
title: 'Confirm',
zIndex: 99999999,
modal: true,
buttons: [{
text: "Yes",
click: function() {
$(this).dialog("close");
dfd.resolve(true);
if ($.isFunction(callback)) {
callback.apply();
}
}
}, {
text: "No",
click: function() {
$(this).dialog("close");
dfd.resolve(false);
}
}],
close: function(event, ui) {
$('#confirm').remove();
}
});
dialog.dialog("open");
return dfd.promise();
}
function deleteUser(id){
// Code you will execute to delete a user or POST back.
}
$(".button").button();
$('.del').click(function(e) {
e.preventDefault();
// your code
$.when(ui_confirm("Are you sure?")).done(function(val) {
if (val) {
console.log("Delete User Confirmed.");
deleteUser($(this).attr("id"));
} else {
console.log("Do not delete user.");
}
});
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
John Smith Delete
You may be able to get away with just executing specific callbacks. That's up to you. This code can then also be used to pass along another function or to use with a prompt() like dialog.
Update
See: Using Url.Action in javascript
For example:
function deleteTestUser(uid, conf){
var url = '#Url.Action("DeleteTestUser", "Home", new {id=' + uid + ', confirm=' + conf + '})';
$.get(url, function(data){
console.log("User " + uid + " Deleted.");
});
}
I would use POST if possible.
function deleteTestUser(uid, conf){
$.post('#Url.Action("DeleteTestUser", "Home")', { id: uid, confirm: conf }, function(data){
console.log("User " + uid + " Deleted.");
});
}

Angular JS : How i can change glyphicon when i click on accordion

I want to change glyphicon glyphicon-plus by glyphicon glyphicon-minus when I click on the accordion and set the color of the active accordion. Have you an idea please for my problem.
page.chtml:
<accordion>
<spotcam class="accordion" data-ng-repeat="spot in Spots" title="{{spot.title}}"> #Html.Partial("~/Views/Common/ConfigurationTemplateDefault.cshtml")
</spotcam>
</accordion>
Controller :
.directive('accordion', function () {
return {
restrict: 'EA',
replace: true,
transclude: true,
template: '<div data-ng-transclude=""></div>',
controller: function () {
var Spots = [];
this.Open = function (selected_Spot) {
angular.forEach(Spots, function (Spot) {
if (selected_Spot != Spot)
Spot.showMe = false;
});
};
this.addSpot = function (Spot) {
Spots.push(Spot);
};
}
};
})
.directive('spotcam', function () {
return {
restrict: 'EA',
replace: true,
transclude: true,
require: '^accordion',
scope: { title: '#' },
template: '<div>' +
'<div class="title"><a class=" more-less glyphicon glyphicon-plus" ng-class="{ 'glyphicon glyphicon-plus': spot != 'selected_Spot', 'glyphicon glyphicon-minus' : spot == 'selected_Spot' }" data-ng-click="toggle()"></a>{{title}}</div>' +
'<div class="body" data-ng-show="showMe" data-ng-transclude=""></div>'+
'</div>',
link: function (scope, element, attrs, accordionController) {
scope.showMe = false;
accordionController.addSpot(scope);
scope.toggle = function () {
scope.showMe = !scope.showMe;
accordionController.Open(scope);
};
}
}
});
One option is to use the scopes variable showMe in the expression
template: '<div>' +
'<div class="title"><a class=" more-less glyphicon glyphicon-plus" ng-class="{true: \'glyphicon glyphicon-minus\', false:\'glyphicon glyphicon-plus\'}[showMe]" data-ng-click="toggle()"></a>{{title}}</div>' +
'<div class="body" data-ng-show="showMe" data-ng-transclude=""></div>'+
'</div>',

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.

Resources