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>
<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;
}
Here is a working jsfiddle. I wish to add attributes (in particular id) to the <li> elements created. My use case is slightly different from the fiddle, rather than using an array, I am getting my data from ajax. In addition I want to give my users flexibility to create new tags if the same are not present in database. To save newly created item list having id's is a much better handle than just plain classes. Can I modify the attributes of the <li> elements created?
My actual code is something like this:
$(".js-data-example-ajax").select2({
ajax : {
url : "/content/search_skills",
dataType : 'json',
delay : 250,
data : function(params) {
return {
q : params.term, // search term
page : params.page
};
},
processResults : function(data, params) {
params.page = params.page || 1;
return {
results : data.items,
pagination : {
more : (params.page * 5) < data.total_count
}
};
},
cache : true
},
escapeMarkup : function(markup) {
return markup;
}, // let our custom formatter work
minimumInputLength : 1,
templateResult : formatRepo,
templateSelection : formatRepoSelection,
tags : true,
createTag : function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
});
function formatRepo(repo) {
if (repo.loading)
return repo.text;
var markup = '<ul class="list-group clear-list m-t">' + '<li class="list-group-item fist-item"><span class="pull-right">' + repo.id + '</span> <span class="label label-success">' + repo.count + '</span> ' + repo.text + '</li>';
return markup;
}
function formatRepoSelection (repo) {
var markup = repo.text;
return markup;
}
And my jsp (html) is:
<select class="js-data-example-ajax" style="width: 100%" multiple="multiple">
//Iterating through database query result to pre-load option items
<option value="<%=skill_objective.get("id")%>" selected="selected"><%=skill_objective.get("id")%> <%=skill_objective.get("name") %></option>
</select>
Here is a working solution:
$(".js-data-example-ajax").select2('data') will give me a hash of all the objects selected.
I tried many things.
i cant initialize default selected items.
The values always "undefined".
Can anyone please help me?
i create de select2, and add options for select.
var selected = [{
"id": 50270924,
"full_name": "zquestz/s",
"description": "Open a web search in your terminal.",
"language": "Go"
}, {
"id": 30494317,
"full_name": "haosdent/s",
"description": "s is a tool for ssh like z for cd",
"language": "Shell"
}];
var $gitElement = $(".select2").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
data:selected,
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: function(repo) {
console.log("res", repo, this);
return '<div class="select2CompanyName">'+repo.full_name+'</div>' +
'<div class="select2CompanyTitle">'+repo.language+'</div>' +
'<div class="select2CompanyTitle">'+repo.description+'</div>';
},
templateSelection: function(repo) {
console.log("sel", repo, this);
return '<div class="select2CompanyResult">' +
'<div class="select2CompanyName">'+repo.full_name+' <br>'+ repo.language +'</div>' +
'<i class="fa fa-pencil-square-o"></i>' +
'</div>';
}
});
for(var i in selected) {
$(".select2").append('<option value="'+selected[i].id+'" selected="selected"></option>');
}
$(".select2").trigger("change");
this version:
jsfiddle
ugly solution would be:
for(var i in selected) {
$(".select2").append('<option value="'+selected[i].id+'" selected="selected">'+JSON.stringify(selected[i])+'</option>');
}
here
working, but ugly
there got a simple way to fix it, u just need to move your template logic to processResults, code should be something like :
function displayItem(repo) {
return {
id : repo.id,
text : '<div class="select2CompanyName">'+repo.full_name+'</div>' +
'<div class="select2CompanyTitle">'+repo.language+'</div>' +
'<div class="select2CompanyTitle">'+repo.description+'</div>'
};
}
....
processResults: function (data, page) {
return {
results: $.map(data.items, displayItem);
};
},
Cost me sometime to find the issue.. I upgrade select2 version to 4.0.2. check fiddle here
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').