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>
Related
i am using select2 control and i want to display or set value which i retrive from database
how to set value to select2 which is retrive from database in ASP.NET MVC
i am using select2 control and i want to display or set value which i retrive from database
how to set value to select2 which is retrive from database in ASP.NET MVC
<script type="text/javascript">
$(document).ready(function () {
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
});
});
</script>
//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;
}
Is there a way I can set this select2 to be disable read-only if there is a value in option.AgentName? I have add the selectElement.select2 method is there anything I can add to the callback?
Is this the correct way to do this? using self.entry.Agent.AgentName != ""?
View
<div class="form-group sentence-part-container sentence-part ng-scope ui-draggable sentence-part-entry-agent sentence-part-with-select2-single" [class.has-errors]="entry.IsInvalid && entry.IsTouched">
<div class="sentence-part-values">
<div class="sentence-part-values-select2-single">
<select class="form-control" style="width: 300px" [(ngModel)]="entry.Agent.VersionKey">
<option *ngFor="let option of agents" [value]="option.VersionKey">{{option.AgentName}}</option>
</select>
</div>
</div>
</div>
ts file
$selectElement.select2({
initSelection: function(element, callback) {
console.log(self.entry.Agent.AgentName);
if (self.entry.Agent.AgentName != "")
{
console.log('disabled');
$selectElement.prop('disabled', true);
}
callback({ id: self.entry.Agent.VersionKey, text: self.entry.Agent.AgentName });
},
placeholder: "Select an agent"
})
.on("change", (e) => {
self.ngZone.run(() => {
self.entry.Agent.VersionKey = $selectElement.val();
self.entry.AgentVersionKey = self.entry.Agent.VersionKey;
let regimenEntryAgent = this.getRegimenEntryAgentByVersionKey(self.entry.Agent.VersionKey);
if (regimenEntryAgent) {
self.entry.Agent.AgentId = regimenEntryAgent.AgentId;
}
self.onSentenceChange(null);
});
})
.on("select2:close", () => {
self.entry.IsTouched = true;
this.validate();
});
You might try to apply some logic in newData.push() method of Select2.
ajax: {
url: '/DemoController/DemoAction',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
// apply some logic to the corresponding item here
if(item.AgentName == "x"){
}
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.AgentName
});
});
return { results: newData };
},
cache: true
},
Update:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes.
For the other Select2 options look Options.
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 Autocomplete UI in mvc .. If user enter some text which is not in list it should alert not in list ....
In View:-
$("#loc").autocomplete({
source: function (request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
if (data.length == 0) {
alert('Please select an item from the list');
document.getElementById('Loc').value = "";
document.getElementById('Loc').focus();
document.getElementById('Loc').style.border = "solid 1px red";
}
else
response($.map(data, function (item) {
document.getElementById('Location').style.border = "solid 1px black";
return { label: item.Name, value: item.Name, id: item.LocationId };
}));
}
})
},
select: function (event, ui) {
$("#locationID").val(ui.item.id);
}
});
in Controller:
public JsonResult AutoLoc(string term)
{
var result = (from r in db.S
where r.Name.ToLower().Contains(term.ToLower())
select new { r.Name, r.id }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
Here suppose we enter 'a' then it will not alert any message . Though 'a' is not in list
when we enter any character which is not in autocomplete list it should alert and make that box as red.
Actually What is happening in 'data' we are getting values because in controller we are writing a query as contains or startwith 'a' so value is returned but as a individual 'a' is not in list that starts with or contains 'a'.
Try this:
$("#loc").autocomplete({
source: function(request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
var found = $.map(data, function(item) {
return {label: item.Name, value: item.Name, id: item.LocationId};
});
if (found.length === 0) {
alert('Please select an item from the list');
$("#loc").val("");
$('#loc').focus();
$('#loc').css("border", "solid 1px red");
} else {
$('#loc').css("border", "none");
}
response(found);
}
});
},
select: function(event, ui) {
$("#locationID").val(ui.item.id);
}
});
In View:
$("#loc").autocomplete({
source: function (request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
var found = $.map(data, function(item) {
return {label: item.Name, value: item.Name, id: item.LocationId};
});
}
});
},
change: function (event, ui) {
var referenceValue = $(this).val();
var matches = false;
$(".ui-autocomplete li").each(function () {
if ($(this).text() == referenceValue) {
matches = true;
return false;
}
});
if (!matches) {
alert('Please select an item from the list');
this.value = "";
this.focus();
this.style.border = "solid 1px red";
}
else {
document.getElementById("submitbutton").disabled = false;
this.style.border = "solid 1px black";
}
}
});
Now when we type 'a' it will alert and show the box border in red color......
This is what i wanted....