Am using JQuery Autocomplete on my templete, but as i get the results the Autocomplete only displays one item despite that the results that are fetched have more that one item. It only shows the first item on the list!
Example:
if i have a result list with ('type1', 'type2', 'type3')
and on the autocomplete i type 't' it only displays type1 on the drop down!
I am a newbie in jquery kindly rectify my mistakes( if any)
My autocomplete code:
$(".fro").each(function() {
$(this).autocomplete({
source : function(request, response) {
$.ajax({
serviceUrl: '${pageContext.request.contextPath}/index.htm',
datatype: "json",
paramName: "fro",
delimiter: ",",
data : {
term : request.term
},
success : function(data) {
response($.map(data.result, function(item) {
$.each(data, function() {
return {
label : this.fro,
value : this.fro
}
});
}));
}
});
},
minLength:1
});
});
My response controller looks like this:
#RequestMapping(value = "/getTags.htm", method = RequestMethod.GET, headers="Accept=*/*")
public #ResponseBody List<SearchFiller> getTags(#RequestParam("fro") String fro) {
return simulateSearchResult(fro);
}
private List<SearchFiller> simulateSearchResult(String fro) {
List<SearchFiller> data=searchFlightDao.fillerList();
List<SearchFiller> result = new ArrayList<SearchFiller>();
for (SearchFiller tag : data) {
if (tag.getFro().contains(fro)) {
result.add(tag);
}
}
return result;
}
Right answer gets appreciated
Let you try this:
$(".fro").each(function() {
$(this).autocomplete({
source : function(request, response) {
$.ajax({
serviceUrl: '${pageContext.request.contextPath}/index.htm',
datatype: "json",
paramName: "fro",
delimiter: ",",
data : {
term : request.term
},
success : function(data) {
dataArray = new Array();
$.each(data, function() {
var t = { label : this.fro, value : this.fro };
dataArray.push(t);
});
response(dataArray);
}
});
},
minLength:1
});
});
Related
I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});
I have a dropdown with multiple options to select. When I select value1 (company), autocomplete should use the service call. When I select value2, lookup should be used.
How can I implement this?
$('#qckSearchKeyword').autocomplete({
serviceUrl: function() {
var option = $('#qck-unspsc').val();
if (option == "country") {
// when country selected through drop down i should use lookup rather then service call
serviceloc = "getCountries";
localStorage.option = "country";
}
if (option == "industry") {
serviceloc = "getSicCode";
localStorage.option = "sicCode";
}
return serviceloc;
},
onSelect: function(suggestion) {
localStorage.tmpSelectedTxt = $.trim($('#qckSearchKeyword').val());
$('#selectFromSuggestions').val("true");
$('#qckSearchKeyword').focus();
},
paramName: "searchTerm",
delimiter: ",",
minChars: 3,
transformResult: function(response) {
// alert(response);
return {
suggestions: $.map($.parseJSON(response), function(item) {
return {
value: item.suggesCode,
data: item.suggesString
};
})
};
}
});
Split up the options for the different autocomplete calls.
Use a data-type on the options you select.
Switch the data-type and extend the proper options
Init autocomplete with proper options
I simply copy/pasted some configuration I've done in the past for this functionality:
...
ajaxOptionsFlight: {
url: '/api/autocomplete/airport/',
type: 'get',
dataType: 'xml'
},
ajaxOptionsHotel: {
url: '/api/locations/hotel/',
type: 'get',
dataType: 'xml'
},
ajaxOptionsCitytrip: {
url: 'http://budapest.onlinetravel.ch/destfinder',
dataType: 'jsonp',
data: {
vendors: 'merger',
client: 'conbe',
filter: 'IATA',
format: 'json',
language: 'en'
}
},
ajaxOptionsCar: {
url: '/api/locations/car/',
dataType: 'json'
},
ajaxOptionsSubstitute: {
url: 'http://gd.geobytes.com/AutoCompleteCity',
dataType: 'jsonp'
},
autocompleteOptions: {
autoFocus: true,
minLength: 1
},
....
After that I make sure I can switch on data-type and hook it on the source parameter of the autocomplete options:
autocompleteOptions = $.extend({}, autocompleteOptions, {
source: type === 'citytrip' ? function (request, response) {
ajaxOptions = $.extend(true, {}, ajaxOptionsCitytrip, {
data: {
name: $.trim(request.term),
language: cookieLanguage
},
success: function (d) {
response($.map(d.Destinations, function (item) {
return {
label: item.name + ', ' + item.country,
value: item.name,
code: item.olt_id
};
}));
}
});
$.ajax(ajaxOptions);
} : type === 'flight' ? function (request, response) {
ajaxOptions = $.extend({}, ajaxOptionsFlight, {
url: ajaxOptionsFlight.url + $.trim(request.term),
success: function (d) {
response($.map($(d).find('airport'), function (item) {
return {
label: $(item).children("displayname").text(),
value: $(item).children("displayname").text(),
code: $(item).children("code").text()
};
}));
}
});
$.ajax(ajaxOptions);
} : type === 'hotel' ? function (request, response) {
// and so on ...
}
});
Not the most elegant way of writing, I admit. But it's basically a simple mapping between data-type and configuration options to provide for autocomplete.
In the end I only call:
input.autocomplete(autocompleteOptions);
And we're done. Hope that makes sense.
Please help. I'm using MVC, razor 3, jquery.
I dynamically create a multi select box when a dropdown selection changes. I bind the multiple selection to a List in my model. And it works, except it passes me the list of selected indice, instead of a list of the selected text. I want selected text, not index of the list. I set the value as text, but I have no luck.
if I manually create the list, everything works. How do I pass a list of selected options back to the controller?
I have this div in my view:
<div class="row-fluid" id="divAvailableAssemblies" hidden ="hidden">
<label class="span4">Available Assemblies:</label>
<select multiple="multiple" class="span8 ui-corner-all" id="Request_SelectingAssemblies" name="Request.SelectingAssemblies">
#*<option value="test">test</option>
<option value="test2">test2</option>*#
</select>
</div>
Here my jquery:
<script type="text/javascript">
$(function () {
$('#ddPartsToCreate').live('change',function () {
var selectedPart = this.value;
if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
{
$("#divAvailableAssemblies").attr("hidden", "hidden");
return;
}
$("#divAvailableAssemblies").removeAttr("hidden");
$.ajax({
type: 'POST',
url: '#Url.Action("GetSelectingAssembliesFromOrder", "Home")',
data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
success: function (response) {
var returnedData = JSON.parse(response);
var selectingAssemblies = $("#Request_SelectingAssemblies");
selectingAssemblies.empty();
for (var assembly in returnedData)
{
//selectingAssemblies.append($('<option >', { value: assembly }).text(returnedData[assembly].Text)).hide().show();
//selectingAssemblies.append($('<option value=' + assembly + '>' + returnedData[assembly].Text + '</option>'));
//selectingAssemblies.append($('<option >', { value: assembly, text: returnedData[assembly].Text }));
//selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));
//$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));
//$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));
//$('<option />', { value: assembly, text: returnedData[assembly].Text }).appendTo(selectingAssemblies);
selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
in the backend, I generate JSON:
foreach (var assembly in pr.ShipParts)
{
sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assembly.Mark.ToString(), assembly.Mark.ToString()));
availableAssemblies.Add(assembly.Mark.ToString());
}
I bind the multiple selection(Request_SelectingAssemblies) with this property in my model:
public List<String> SelectingAssemblies
{
get
{
return _SelectingAssemblies;
}
set
{
_SelectingAssemblies = value;
}
}
private List<String> _SelectingAssemblies = new List<string>();
When it gets to my action in the controller, SelectingAssemblies has index instead of the actual text. But I set the value of each option as text. If I set the option manually, they will show in source page and return the text. But since I dynamically create the options, they don't show in source page. I don't know how I can make MVC understand dynamic data.
In the picture, the list of CX001, RBX001, RBX002 is dynamically created. if I hit F12 in IE, I will see them created correctly in the DOM. If I choose CX001 and RBX002, SelectionAssembies will have 0 and 2.
Thanks
This is the latest and working code, thanks to #StephenMuecke:
<script type="text/javascript">
$(function () {
$('#ddPartsToCreate').live('change',function () {
var selectedPart = this.value;
if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
{
$("#divAvailableAssemblies").attr("hidden", "hidden");
return;
}
$("#divAvailableAssemblies").removeAttr("hidden");
$.ajax({
type: 'POST',
url: '#Url.Action("GetSelectingAssembliesFromOrder", "Home")',
data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
success: function (response) {
var returnedData = JSON.parse(response);
var selectingAssemblies = $("#Request_SelectingAssemblies");
$.each(returnedData, function (index, item) {
selectingAssemblies.append($('<option></option>').val(item.Value).html(item.Text));
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
public ActionResult GetSelectingAssembliesFromOrder(String orderNumber)
{
return Json(model.GetSelectingAssembliesFromOrder(orderNumber), JsonRequestBehavior.AllowGet);
}
public String GetSelectingAssembliesFromOrder(String orderNumber)
{
//...
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var assembly in pr.ShipParts)
{
string assemblyName = assembly.Mark.Trim();
sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assemblyName, assemblyName));//JSON to build the list
//...
}
sb.Append("]");
sb.Remove(1, 1);//remove extra comma
_db.SaveChanges();
return sb.ToString();
}
I'm almost there and on my first jquery autocomplete script... I just need some help to figure out how to return the founded elements has link so that we can click on them.
Here a part of my js code:
$(document).ready(function() {
var attr = $('#leseulsteve_lieuxbundle_lieutype_nom').attr('data-url');
var searchRequest = null;
$("#leseulsteve_lieuxbundle_lieutype_nom").autocomplete({
minLength: 3,
source: function(request, response) {
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = $.ajax({
url: attr,
method: 'get',
dataType: "json",
data: {nom: request.term},
success: function(data) {
searchRequest = null;
console.log(data);
$.each(data, function (i, v) {
--- SOME VARIABLE I GUESS TO STORE THE RESULT ---
});
return THE 'SOME VARIABLE;
}
}).fail(function() {
searchRequest = null;
});
}
});
});
In the console I got this from the console.log(data) line:
Object {École secondaire De Rochebelle: "/GestigrisC/app_dev.php/lieux/voir/2", École secondaire la Camaradière: "/GestigrisC/app_dev.php/lieux/voir/3"}
I have control over how the JSON feed is built, so no worries there if it's helps to build that super mysterious for me now variable to return.
Thanks a lot for the help!
If you just want to build links and put them into your HTML then I think you're looking for something like this:
success: function(data) {
var html = '';
$.each(data, function (i, v) {
html += ''+i+'';
});
$('#container_id').html(html);
}
Got it right, thanks for your help :)
$(document).ready(function() {
var attr = $('#leseulsteve_lieuxbundle_lieutype_nom').attr('data-url');
var searchRequest = null;
$("#leseulsteve_lieuxbundle_lieutype_nom").autocomplete({
minLength: 3,
source: function(requete, reponse) {
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = $.ajax({
url: attr,
method: 'get',
dataType: "json",
data: {nom: requete.term},
success : function(donnee){
reponse($.map(donnee, function(objet){
return {label: objet.type + ' | ' + objet.label, type: objet.type, id: objet.id};
}));
}
}).fail(function() {
searchRequest = null;
});
},
select: function (event, ui) {
$('#leseulsteve_lieuxbundle_lieutype_nom').val(ui.item.label);
$('#leseulsteve_lieuxbundle_lieutype_type').val(ui.item.type);
$('#leseulsteve_lieuxbundle_lieutype_id').val(ui.item.id);
$('#formulaire').submit();
}
});
});
I have the following JavaScript code to do an autocomplete:
$("#Technology2_Tag").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Content("~/Switch/AutoComplete2")",
dataType: "json",
minLength: 2, delay: 2000,
data: {
term: request.term,
SearchBy: $("#ChoiceTag").prop("checked") ? $("#ChoiceTag").val() : $("#ChoiceName").val(),
},
success: function (data) {
response(data);
}
});
},
});
And I am returning the autocomplete records as JSON:
public ActionResult AutoComplete2(string term, string SearchBy)
{
if (SearchBy == "Tag")
{
var tech = repository.AllFindTechnolog(term).OrderBy(p => p.Tag).Select(a => new { label = a.Tag }).ToList();
return Json(tech, JsonRequestBehavior.AllowGet);
}
else
{
var tech = repository.FindActiveResourceByName(term, true).OrderBy(p => p.RESOURCENAME).Select(a => new { label = a.RESOURCENAME }).ToList();
return Json(tech, JsonRequestBehavior.AllowGet);
}
}
But my question is how I can show a dialog the contains additional info about the record, when the user hovers over an autocomplete record.
what i am thinking of is as follows:
when the user hovers over any autocomplete record, to fire a JavaScript function.
the function calls an action method, that returns JSON.
to build the dialog box using the returned JSON object.
First you need to create a div let's say with the id=mydiv which can be a dialog. Initialize it as a dialog.
Then in your autocomplete use focus event. Which will handle an Ajax function which will call an Action (this action can return a Partial view) and will fill your div with the description.
$("#mydiv").dialog();
$ ("#Technology2_Tag").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Content("~/Switch/AutoComplete2")",
dataType: "json",
minLength: 2, delay: 2000,
data: {
term: request.term,
SearchBy: $("#ChoiceTag").prop("checked") ? $("#ChoiceTag").val() : $("#ChoiceName").val(),
},
success: function (data) {
response(data);
}
});
},
focus: function(event,ui){
var element =ui.item.val;
$.ajax({
url: "#Url.Content("~/Switch/ActionDescription")",
dataType: "json",
data: {
hoverelment: element },
success: function (data) {
$('#myDiv').append(data);
$('#myDiv').show();
}
});
}
});
I gave you lines, you have to create another action which will receive a parameter, can send a partial view or just string.
public ActionResult ActionDescription(string hoverlement)
{
.........//linq queries to retrieve description by hoverelement
}
I hope it will help.