Please, help.
html:
<select id="select-client" class="form-control" style="width: 350px;"></select>
js:
$("#select-client").select2({
ajax: {
url: _app.url + "finduser",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 2,
templateResult: formatClientRepo,
templateSelection: formatClientRepoSelection,
placeholder: "Enter user name"
});
And as result I've received this: http://prntscr.com/76jxvi
I found many variants, such as empty option in select, or write placeholder in select, but nothing.
https://jsfiddle.net/xqhp0z0x/1/
in this example if we delete || repo.text from formatRepoSelection it will not work. Because the repo.text is placeholder.
P.S. select2 4.0 do not need to empty option tag for placeholder working
Related
I am trying to make an autocomplete functionality for my page.
I have a textbox and I would like to make suggestions from my database.
I have this JsonResult in my controller:
public JsonResult ItemAutocomplete(string term)
{
var result = _db.SelectTable("SELECT [i].[Name] from [dbo].[Item][i] WHERE [i].[Name] LIKE #0", SqlDb.Params(term +"%"));
return Json(result, JsonRequestBehavior.AllowGet);
}
and in my view:
#Scripts.Render("~/bundles/jqueryui")
<h2>jQuery AutoComplete</h2>
<script>
$(function () {
$('#tags').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("ItemAutocomplete")',
extraParams: { term: $('#tags').val(),
dataType: "json",
contentType: 'application/json, charset=utf-8',
data: {
term: $("#tags").val()
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
The problem is that my ItemAutocomplete jsonResult always receives a null param... even if I call it directly from localhost, like this: "localhost/Appointment/ItemAutocomplete/item1".
Use (request.term) below
data: { term: request.term }
instead of
data: { term: $('#tags').val() }
In Autocomplete Text box, search string detect by "request.term".
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 try to store an identifier into an hiddenfield when a value is selected with a jquery autocomplete field.
But the select event is never fired and I dont't see why..
here is my code
$(document).ready(function () {
$('#test').autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Controller/Method", type: "POST", dataType: "json",
data: { Comparaison: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.text, value: item.text, id : item.value };
}));
},
select: function (event, ui) {
alert("selected");
//$("#idProprio").val(ui.item.id);
}
});
},
});
});
The autocompletion is properly working, I can see the values, select one but when I select a value nothig happens..
I believe your curly braces are wrong. select is being set as part of the ajax parameter, not autocomplete:
$(document).ready(function () {
$('#test').autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Controller/Method", type: "POST", dataType: "json",
data: { Comparaison: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.text, value: item.text, id : item.value };
}));
}
});
},
select: function (event, ui) {
alert("selected");
//$("#idProprio").val(ui.item.id);
}
});
});
I am using jEditable to update a value on my MVC model and back to the database successfully. The updated value appears on the webpage which is exactly what I want. I also want to update another control on the page (as it is a calculated value using the updated field). What is the best way to do this? Is there a hook into a successful jEditable update that I can add some jQuery into to refresh the other control?
My jEditable call :
$(function () {
$(".editable_textarea").editable("#Url.Action("UpdateSharePrice","Home")", {
indicator: "<span style='color:#FF0000;'>Saving...</span>",
type: 'text',
submitdata: { _method: "put" },
select: true,
submit: 'OK',
cancel: 'X',
width: '40',
cssclass: "editable",
tooltip: 'click to edit...',
onblur: "submit"
});
});
Thanks
Colin.
Well, I figured it out in the end
You can use the JEditable callback method to get the parameters used to call the controller method:
$(function () {
$(".editable_textarea").editable("#Url.Action("UpdateSharePrice","Home")", {
indicator: "<span style='color:#FF0000;'>Saving...</span>",
type: 'text',
select: true,
submit: 'OK',
cancel: 'X',
width: '40',
cssclass: "editable",
tooltip: 'click to edit...',
onblur: "submit",
callback: function(value, settings)
{
var fundId = this.id;
$.ajax({
url: '#Url.Action("GetMarketValue", "Home")',
type: 'POST',
data: { id : fundId },
success: function (data) {
$('#marketValueDiv_' + fundId).html(data);
}
});
}
});
});
This parameter can then be used to do an ajax post to another action method that returns the calculated field from the model:
public ActionResult GetMarketValue(int id)
{
if (ModelState.IsValid && id > 0)
{
BaseFund targetFund = _context.Funds.Find(id);
return PartialView("GetMarketValue", targetFund);
}
else
{
return PartialView("0.00");
}
}
The success callback on the ajax call is then used to update the appropriate div html content
Hi I got a problem with change event.
By documntation there should be object ui.item
After an item was selected; ui.item refers to the selected item. Always triggered after the close event.
But when I try it ui.item is undefined :( I want unset s_town_id when input in autocomplete doesn't match with data from script.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
// ui.item is undefined :( where is the problem?
$("#s_town_id").val(ui.item.id);
}
});
});
I find out solution where I testing event.originalEvent.type if it is meneuselected or not and after fail I unset s_town_id. But any better solution is still wellcome.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
try
{
if(event.originalEvent.type != "menuselected")
{
// Unset ID
$("#s_town_id").val("");
}
}
catch(err){
// unset ID
$("#s_town_id").val("");
}
}
});
});
if ui.item is not defined that means your json source is not well formed.
You have to send a json source like this:
[{"label":"Jean","value":1},{"label":"carl","value":2}]
You can add more key to the array but at least you have to set "label" and "value".
Check the json string.
Also I reckon you to use the last version of autocomplete 1.8.1 at the moment