JQuery UI Autocomplete Multiple Textbox on ASP MVC Razor - javascript

I return a class object but only XRCFOR textbox is populate correctly. Select events seems no work.
Through a WebServe I return object items. Select event on a row however is only populated the XRCFOR textbox. Here is the Html/razor/Jquery code. Thanks.
<td>
#Html.EditorFor(model => model.XRUDBF, Functions.GetAdditionalViewData(ViewData["PageStatus"].ToString(), ViewData["PageReadonly"].ToString(), "form-control"))
#Html.EditorFor(model => model.XRCFOR, Functions.GetAdditionalViewData(ViewData["PageStatus"].ToString(), ViewData["PageReadonly"].ToString(), "form-control"))
#Html.EditorFor(model => model.XRCFORDescription, new {htmlAttributes= new { #class = "form-control", #readonly = "readonly" }})
<script type="text/javascript">
$("#XRCFOR").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Zoom/GetFOR/",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.B5CFOR + " - " + item.B5RGS1, value: item.B5CFOR
};
}))
}
})
},
select: function (event, ui) {
$("#XRUDBF").val(ui.item.B5CUDB);
$("#XRCFOR").val(ui.item.B5CFOR);
$("#XRCFORDescription").val(ui.item.B5RGS1);
},
//messages: {
// noResults: '',
// results: function () { }
//},
minLength: 1
});
</script>
</td>

I've found this solution
success: function (data) {
response($.map(data, function (item) {
return {
label: item.B5CFOR + " - " + item.B5RGS1, value: item.B5CFOR, extravalue: item
};
}))
}
and then
select: function (event, ui) {
$("#XRUDBF").val(ui.item.extravalue.B5CUDB);
$("#XRCFORDescription").val(ui.item.extravalue.B5RGS1);
},
works fine!

Related

Autocomplete dropdownlist not working

I went through a lot of guides and stacloverflow posts, but i still don't manage to make it work. I'm still new in javascript, and it's hard for me to figure if it's the script or not.
The main issue i got is the fact I'm not able to debbug it properly, i mean, i can't find where and why it's not working, i just know it doesn't.
Here is my Controller :
Entities db = new Entities();
// GET: DynamicListe
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Index(string Prefix)
{
//Searching records from list using LINQ query
var client = (from c in db.Clients
where c.Nom.Contains(Prefix)
select new { c.Nom });
return Json(client, JsonRequestBehavior.AllowGet);
}
Here is my View :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#client").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
for (var i = 0; i < data.length ; i++) {
customer[i] = { label: data[i].Value, Id: data[i].Key }
}
}
});
response(customer);
},
messages: {
noResults: "", results: ""
}
});
})
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="client">
<div class="col-md-12">
#Html.TextBox("client")
</div>
</div>
</div>
}
I got the right amount of answers (when i press "w" i got 13 results which is correct according to my db), but it's all empty. I've tried severals ways to display the json datas, but i don't know how to make it work..
Edit : correct controller and view :
view :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#client").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Value};
}))
}
});
},
messages: {
noResults: "", results: ""
}
});
})
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="client">
<div class="col-md-12">
#Html.TextBox("client")
</div>
</div>
</div>
}
controller :
[HttpPost]
public JsonResult Index(string Prefix)
{
List<SelectListItem> list = new List<SelectListItem>();
var client = (from c in db.Clients
where c.Nom.Contains(Prefix)
select c).ToArray();
for (int i = 0; i < client.Length; i++)
{
list.Add(new SelectListItem
{
Text = client[i].Nom,
Value = client[i].ClientID.ToString()
});
}
return Json(list, JsonRequestBehavior.AllowGet);
}
You're returning your response before it has been received.
In here
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
for (var i = 0; i < data.length ; i++) {
customer[i] = { label: data[i].Value, Id: data[i].Key }
}
}
});
response(customer);
},
Move the line response(customer) inside the ajac success callback.
You textbox does not have an ID. you have to add for yout textbox : #Id="client"

.Val() set value, but not show into TextBox

So, i have a problem with a function un JS, how call a Ajax request :
function editDataAddress(idPartnerAddress) {
// simplified
var url = "#Url.Action("SelectAddressToEdit", "Partners", idPartnerAddress)"
$.ajax({
url: url,
dataType: 'json',
success: function (data) {
var adresse = data.Address;
var zip = data.Zip;
var locality = data.Locality;
var idLocalite = data.IdLocality;
//alert("locality : "+locality);
$("#ZipSwiss").empty()
$("#ZipSwiss").append($('<option></option>').val(idLocalite).html(zip));
$('#PartnerAdresse_Locality').val(locality)
// This line confirm i don't have another PartnerAdresse_Locality in my page
console.log('ID Test:', $('[id=PartnerAdresse_Locality]').length, $('[id=PartnerAdresse_Locality]').get())
}
});
}
<div class="col-md-4" id="divZipSwiss">
#Html.DropDownListFor(model => model.ZipSwiss, ViewBag.localiteList as IEnumerable<SelectListItem>, "Recherche...", new {#class = "form-control", style = "width : 100%;"})
</div>
<div class="col-md-5">
#Html.TextBoxFor(model => model.PartnerAdresse.Locality, new { #class = "form-control" })
</div>
The problem is, when i call the function, the ajax return all value, and put in the 4 first var (adresse, zip, locality, idlocalite) correctly
When i do the $('#PartnerAdresse_Locality').val(locality), the value is set in the HTML, but not show :
and the HTML :
<input class="form-control" id="PartnerAdresse_Locality" name="PartnerAdresse.Locality" type="text" value="Geneva">
The NPA (Zip) is okay, and the locality value is filled, but not showing
if now I comment $("#ZipSwiss").append($('<option</option>').val(idLocalite).html(zip));
the locality appears, but of course, no more the NPA (zip) because of the comment.
i'm really lost, somebody can help me?
Following my explanation, i founded the solution by comment some code line :
for my ZipSwiss, I Have a select2 DDL :
$('#ZipSwiss')
.select2({
language: lang,
minimumInputLength: 2,
minimumResultsForSearch: Infinity,
closeOnSelect: true,
ajax: {
url: '#Url.Action("SearchLocalite", "Partners")',
dataType: 'json',
delay: 200,
data: function(params) {
return {
searchTerm: params.term
};
},
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
id: item.IdLocalite,
text: item.ZipCode,
name: item.Name
}
})
}
},
cache: true
},
templateResult: function(item) {
if (item.loading)
return item.text;
return item.text + " | " + item.name;
},
templateSelection: function (item) {
$("#PartnerAdresse_Locality").val(item.name);
return item.text;
},
escapeMarkup: function(markup) {
return markup;
}
});
The line : $("#PartnerAdresse_Locality").val(item.name); is called ALWAYS when you update the selection. it's mean, the value is null.
Thanks ^^

jquery ui autocomplete custom data (item undefined )

My Script
$("#NameSearch").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
url: "/home/universalsearch/" + document.getElementById("filterUniversalSearchList").value + "/" + $("#NameSearch").val(),
type: "POST",
dataType: "json",
data: {
searchFilter: document.getElementById("filterUniversalSearchList").value,
term: request.term,
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.EmployeeName, id: item.EmployeeID}
}))
}
});
},
focus: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<div>" + item.label + "<br>" + item.id + "</div>")
.appendTo(ul);
};
});
Controller:
public JsonResult UniversalSearch(string searchFilter, string searchText)
{
var Employees = _home.GetEmployeeDetails(searchFilter, searchText);
return Json(new { data = Employees }, JsonRequestBehavior.AllowGet);
}
Problem I'm facing is in autocomplete dropdown I'm getting as undefined.
From controller it return as object array
I think I made mistake in binding data improperly.
dropdown result shows as undefined.
Is this problem due to jqueru-ui versions ?

Want to prevent selecting specific item in jQuery UI AutoComplete

I am developing textbox with autocomplete using jQuery UI Autocomplete.
After that, I can create textbox with autocomplete, but one issuce has occured now.
In my textbox, I want to prevent selecting specific item from autocomplete list.
If I select specific item, Autocomplete list display again or not to close.
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
});
});
});
If someone know answer, please teach me.
Based on the example from here: How to disable element in jQuery autocomplete list
I think this code will work for you:
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
//Add the .ui-state-disabled class and don't wrap in <a> if value is empty
var id = item.id
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
} else{
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
};
});
If you can provide a working version of your code (the items can also be from a predefined list, not based on ajax call) it will be much easier to help.

jQuery autocomplete with multiple items not working

I am working on jQuery autocomplete which as two items in a <ul>.
I am getting json item from $.getJSON function and the json object looks like :
[{
"merchant_name": "Myntra",
"merchant_details": "Flat Rs.225 Cashback"
}, {
"merchant_name": "Adlabs imagica",
"merchant_details": "Rs 170 per sale"
}, {
"merchant_name": "godaam",
"merchant_details": "Rs 140 per sale"
}, {
"merchant_name": "Homeshop18",
"merchant_details": "Upto 8% Cashback"
}]
My function looks as follows:
$('#search_bar').keyup(function(e) {
var searched = $('#search_bar').val()
$.getJSON('<?php echo base_url();?>get_data', 'title=' + searched, function(result) {
var elements = [];
$.each(result, function(i, val) {
elements.push({
'merchant_name': val.merchant_name,
'merchant_details': val.merchant_details
})
}) $('#search_bar').autocomplete({
delay: 0,
source: elements,
select: function(event, ui) {
$("input#search_bar").val(ui.item.merchant_name + " / " + ui.item.merchant_details);
$("#get").click();
}.data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a><strong>" + item.merchant_name + "</strong> / " + item.merchant_details + "</a>").appendTo(ul);
};
})
})
});
I am not able to proceed forward.
Please help me to solve this one.
I wrote this for one of my projects and it works perfectly. I'm not sure why you are detecting keyup when autocomplete does that for you... But this snippet should give you all the functionality you need.
$("#edit_profile .location").autocomplete({
source: function(request, response) {
$.ajax({
url: BASE_URL + "lib/ajax.php",
type: "GET",
data: "autocomplete_location=1&term=" + request.term,
cache: false,
success: function(resp) {
try {
json = $.parseJSON(resp);
} catch (error) {
json = null;
}
//
if (json && json.status == "OK") {
//
response($.map(json.predictions, function(item) {
return {
label: item.description,
value: item.description
}
}));
//
}
}
});
},
minLength: 1,
change: function (event, ui) {
if (!ui.item){
$(this).val("");
}
}
});

Categories

Resources