Selecting an autocomplete item is not working - javascript

I have the following field inside my asp.net mvc web application:-
<input class="push-up-button searchmargin" placeholder="Search by tag.." name="searchTerm2" data-autocomplete-source= "#Url.Action("AutoComplete", "Home")" type="text" style="margin-top:8px"/>
and i wrote the following autocomplete function:-
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"), minLength: 1, delay: 1000,
create: function () {
$(this).data("autocomplete")._renderItem = function (ul, item) {
return $('<li>').append('<a>' + item.label + '<br>' + item.resourcename + ' | ' + item.customername + ' | ' +item.sitename + '<hr>' +'</a>')
.appendTo(ul);
};
}
});
});
Currently the auto complete is working well (the result list will be displayed), but the problem is that if i select an item from the auto complete result it will not be rendered inside the auto complete field.and when i check the firebug i noted the following error , when selecting an auto complete item:-
TypeError: item is undefined
[Break On This Error]
self.element.val( item.value );
For example if i start typing the following words "i am" , then i select "I am writing" from the autocomplete list result , then the autocomplete field will have the "I am" text instead of the select "I am writing". Can any one advice , what is causing this problem?
Thanks
EDIT
i edited my autocomplete as follow, by adding focus & select :-
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"), minLength: 1, delay: 1000,
focus: function (event, ui) {
$("input[data-autocomplete-source]").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("input[data-autocomplete-source]").val(ui.item.label);
return false;
},
create: function () {
$(this).data("autocomplete")._renderItem = function (ul, item) {
return $('<li>').append('<a>' + '<b>'+item.label + '</b><br>' + '<span style="color:#8e8e8e ">' + item.resourcename + ' | ' + item.customername + ' | ' + item.sitename + '<hr style="padding: 0px; margin: 0px;">' + '</span></a>')
.appendTo(ul);
};
}
});
});
but i wil get the following error when i am trying to select an autocomplete item:-
TypeError: ui.item is undefined

Please add "Select" event and try below
$( "input[data-autocomplete-source]" ).autocomplete({
select: function( event, ui ) {
$( "input[data-autocomplete-source]" ).val( ui.item.yourValueProperties);
return false;
}
});
***Note : yourValueProperties= like customername ***

Related

Store previous kendo dropdownlist option using keyboard

I want to store the previously selected option when navigating with the keyboard. I have achieved this if the user clicks on the drop down but it doesn't store the option if navigated with the keyboard.
Code:
CreateDropDown: function (id) {
var me = IndexController;
$("#Drop" + id + "").kendoDropDownList({
name: "drop" + id,
dataTextField: "text",
dataValueField: "value",
valueTemplate: '<i class="#:data.icon#"> </i></span><span>#:data.text#</span>',
template: '<i class="#:data.icon#"> </i>' +
'<span class="k-state-default"><p>#: data.text #</p></span>',
dataSource: me.variable.options,
index: 0,
change: me.onChange,
open: function (e) {
me.options.previousOption = e.sender.value();
}
});
me.AddShortText(id, "Short Answer");
}
and I can use the value:
AddShortText: function (a, ChoiceText) {
var me = IndexController;
if (me.options.previousOption == "2" || me.options.previousOption == "3")
$("#TypeDiv" + a).children(".toRemove").remove();
else
$("#TypeDiv" + a).children(".group").remove();
$("#TypeDiv" + a).append('<div class="group" style="width:50%">\
<input id="Answer'+ a + '" type="text" class="inputHighlight" disabled >\
<span class="bar"></span>\
<label class="labelHighlight">'+ ChoiceText.trim() + '</label>\
</div>');
},
GIF:
Thank you in advance
Use the select event https://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist/events/select
The select function is triggered both with keys or mouse
$("#Drop").kendoDropDownList({
// your code
select: function(e) {
me.options.previousOption = e.sender.value();
}
});

ajax autocomplete same data with multiple textbox jquery

i have one issue with jquery autocomplete, its working with one textbox perfect but when i create multiple textbox using jquery with same ID at that time its working for only first textbox not for another textbox .
my question is i want to create multiple textbox and implement same autocomplete data with all text box
this is my code for create textbox using jquery
var totalSelect = $('#max_player').val();
$('#competitor_box').empty();
for (var i = 1; i <= totalSelect; i++) {
var ajaxauto = '<div class="form-group col-sm-3"><label for="tournament_name">Pocker # '+i+'</label><input id="autocomplete-ajax" type="text" class="form-control" autocomplete="off"></div>';
$('#competitor_box').append(ajaxauto);
}
this code for ajax autocomplete
$('#autocomplete-ajax').autocomplete({
// serviceUrl: '/autosuggest/service/url',
lookup: countriesArray,
lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
return re.test(suggestion.value);
},
onSelect: function(suggestion) {
$('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
onHint: function (hint) {
$('#autocomplete-ajax-x').val(hint);
},
onInvalidateSelection: function() {
$('#selction-ajax').html('You selected: none');
}
});
please help me for this issue its very important for me
thanks all.
var totalSelect = $('#max_player').val();
$('#competitor_box').empty();
for (var i = 1; i <= totalSelect; i++) {
var ajaxauto = '<div class="form-group col-sm-3"><label for="tournament_name">Pocker # '+i+'</label><input class="txtAutocomplete" type="text" class="form-control" autocomplete="off"></div>';
$('#competitor_box').append(ajaxauto);
}
Autocomplete function
$('.txtAutocomplete').autocomplete({
// serviceUrl: '/autosuggest/service/url',
lookup: countriesArray,
lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
return re.test(suggestion.value);
},
onSelect: function(suggestion) {
$('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
onHint: function (hint) {
$('#autocomplete-ajax-x').val(hint);
},
onInvalidateSelection: function() {
$('#selction-ajax').html('You selected: none');
}
});
why did you use the same ID for severals input ? use classes if you have to tag multiples elements, for example .autocomplete-ajax-input on each textbox. And then declare your autocomple function with $('.autocomplete-ajax-input').autocomplete

handling "No results" with Jquery Autocomplete

Hey I'm trying to return a message when there are no results for the users current query! I have looked all over the net and there are similar scenarios, but I can't seem to get it working with my code below!
Can anyone help me figure this out please, as I am pulling my hair out trying to fix it!
I need to maintain the ability to use the keyboard to scroll down through the results.
Thanks in advance.
HTML
<div id="search_box">
<form id="search_form" autocomplete="off" action="" onSubmit="return false;">
<input type="text" id="suggestSearchBox" value="Search by City or Hotel Name" onClick="this.value='';" />
</form>
</div>
Javascript
NOTE: The remote data source is called "dataLocCodes", which is a javascript array
// JavaScript Document
$(function() {
$("#suggestSearchBox").focus().autocomplete(dataLocCodes, {
max: 15,
selectFirst: true,
matchContains: true,
formatItem: function(row, i, max){
if (row.hotelId) {
return row.accomName + ' - ' + row.city + ' - ' + row.country;
} else {
return row.city + ' - ' + row.country;
}
}
}).result(
function(event, row, formatted) {
$("input#suggestSearchBox").val(row.city + ' - ' + row.country);
var param = row.locparam;
var encoded_url = param.replace(/ /gi,"+");
encoded_url = encoded_url.replace(/&/gi,"amp");
window.location.href = "hotels.html?location=" + encoded_url;
});
});
There are a couple of ways to handle this. You can either create a source method so that if the results from the filter are empty, you add "no results" as a value, or you handle the response event to display a message that no results where returned in your ui. If using the source method, then add a select handler to prevent No Result from being a value.
var availableTags = ['Abc', 'Def', 'ghi'];
$('#noresults').autocomplete({
source: function (request, response) {
var responses = $.ui.autocomplete.filter(availableTags, request.term);
if (responses.length == 0) responses.push('No Result');
response(responses);
},
response: function (event, ui)
{
if (ui.content.length == 0) {
console.log('No results');
}
},
select: function (event, ui) {
// don't let no result get selected
return (ui.item.value != 'No Result');
}
});

Autocomplete using data attribute for source?

Can I use data attribute for the source of my autocomplete?
for example
HTML
<input type="text" class="autocomplete" data-source="/search.php" />
Javascript
$(".autocomplete").autocomplete({
source : $(this).data('source'),
minLength:1,
select: function( event, ui ) {
console.log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
I tried it but it always gives me an error.
What's wrong with my code?
Uncaught TypeError: Property 'source' of object #<Object> is not a function
In source you can use this.element which refers to the input
$(".autocomplete").autocomplete({
source : this.element.attr('data-source'),
minLength:1,
select: function( event, ui ) {
console.log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
here's the fix
$('.autocomplete').keypress(function(){
$(this).autocomplete({
source: $(this).data('source'),
minLength: 1,
select: function(event, ui) {
console.log(ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value);
}
});
});
I added a keypress function so that it will get the current element.
The this pointer does not refer to the .autocomplete element -- this only equals the selected element inside callbacks executed by jquery. It looks like you want to do something like this:
$(".autocomplete")
.autocomplete({
minLength:1,
select: function( event, ui ) {
console.log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
})
.each(function() { // Goes through `.autocomplete` elements and sets source
$(this).autocomplete("option", "source", $(this).data('source'));
})
;
every keystroke of autocomplete will trigger a remote request if the source is a url. what you can do to prevent that is to "pre-fetch" the data (make sure to return a JSON-valid array), then add the return data as the source for the autocomplete. that way, data is only fetched once, and autocomplete will reference to that data.
jQuery autocomplete already has a filtering capability. you just need a full list of items and it will filter it for you.
//get all input boxes with class "autocomplete"
$('.autocomplete').each(function(){
//reference input and get it's url
var input = $(this);
var url = input.data('source');
//get list array only ONCE for each input using their specified urls
$.get(url, function(data) {
//when request is received, add autocomplete using the returned data
input.autocomplete({
source: data,
minLength: 1,
select: function(event, ui) {
console.log(ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value);
}
});
});
});

How to redirect to another page with jQuery Autocomplete item click

I'm stumped with this one, I've been at it hours, trying to get jQuery autocomplete to go to another page on the site when an item is clicked in the suggestions list.
Anyone know how to do this? Here is my code :
$(':input[data-autocomplete]').autocomplete({
source: $(':input[data-autocomplete]').attr("data-autocomplete"),
delay: 0,
select: function (event, item) {
//window.location.replace("http://www.example.com/Profile/Details/1");// Works but totally unacceptable, browser history lost etc..
//alert("Item Clicked"); //Fires Ok
}
}).data("autocomplete")._renderItem = function (ul, item) {
var MyHtml = '<a id="ItemUrl" href="/Profile/Details/' + item.PartyId + '"' + ">" +
"<div class='ac' >" +
"<div class='ac_img_wrap' >" +
'<img src="../../uploads/' + item.imageUrl + '.jpg"' + 'width="40" height="40" />' +
"</div>" +
"<div class='ac_mid' >" +
"<div class='ac_name' >" + item.value + "</div>" +
"<div class='ac_info' >" + item.info + " PartyId :" + item.PartyId + "</div>" +
"</div>" +
"</div>" +
"</a>";
return $("<li></li>").data("item.autocomplete", item).append(MyHtml).appendTo(ul);
};
As you can see I have used custom HTML in the _renderItem event, my custom HTML creates an anchor tag with the id passed in from the source, this looks ok, the link is formed correctly in the browser bottom left corner (I'm using Chrome)
<a href='/Profile/Details/id' >some other divs & stuff</a>
The problem is that when I click the link nothing happens, I have tried using the select event but item is null so can't get item.PartyId to force a manual jump.
How can I get the click event working?
It might late to answer it, but I have done this with the following code:
$(document).ready(function() {
$('#txtSearch').autocomplete({
minLength: 3,
source: "handlers/SearchAutoComplete.ashx?loc=" + $('#hfLocation').val(),
select: function(event, ui) {
doSearch(ui.item.label, ui.item.city);
}
});
});
function doSearch(term, location) {
window.location.href = 'Search.aspx?q=' + term + '&loc=' + location;
}
After a few days of head banging (not moshing kind) I've come up with the following:
$(':input[data-autocomplete]').autocomplete({
source: $(':input[data-autocomplete]').attr("data-autocomplete"),
delay: 0,
select: function (event, ui) {
var q = ui.item.PartyId;
if (q != "") {
$('#hidPID').val(q);
$('#ac_submit').trigger('click');
}
}).data("autocomplete")._renderItem // -->>> the rest of the code same as above
The issue was (event, item) should have been (event, ui) and to get the value of the item you use ui.item.PartyId (in my case PartyId is declared in the source : above)
So on my original form I had two html inputs 1-hidden ID, 2-Submit & as you can see in the select : function above I set the ID & trigger the submit (so now the user just picks an item and off they go to the controller which performs the RedirectToView & NOT this code as it doesn't seem correct to use location in this instance)
I Hope this saves someone some time as the jQuery autocomplete docs dont make it too clear.

Categories

Resources