get name of list item click in autocomplete in jquery - javascript

Hi all,
In my application I am using autocomplete, I have list as
<p>
<input type="text" id="searchField" placeholder="Categories">
<ul id="suggestions" data-role="listview" data-inset="true"></ul>
</p>
I have one array name myArray and using autocomplete as:
$("#searchField").autocomplete(
{
target: $('#suggestions'),
source: myArray ,
link: 'target.html?term=',
minLength:0
});
Now I want to get the list item name on which I click and use that variable in target.html file. How to get that? Thanks in advance.

From their help docs.
Callback
When using the optional callback function autoComplete will only execute code found within the callback. The click event object is passed into the callback function for use in accessing the information contained in the selection. Here's one use case:
$("#searchField").autocomplete("update", {
source: [ "foo", "bar", "baz" ],
minLength: 3,
callback: function(e) {
var $a = $(e.currentTarget); // access the selected item
$('#searchField').val($a.text()); // place the value of the selection into the search box
$("#searchField").autocomplete('clear'); // clear the listview
}
});
OPTION 1
This section will allow you to access the text field
$('#searchField').val($a.text()); // or $a.value()
so do something like this inside the callback event
window.location.replace("http://stackoverflow.com?target=" + $a.text());
OPTION 2
It seems like they expect the result set to be in this format (text & value), so if you'd need other values, you'd need to resort to the jquery autocomplete (which this component is based on)
$('#some_id').autocomplete({
source: function (request, response) {
$.ajax({
url: 'some_url',
dataType: "json",
data: {
filter: request.term
},
success: function (data) {
response($.map(eval(data), function (item) {
return {
label: item.Text,
value: item.Value,
extra_value: item.Extra_Value
}
}));
}
})
},
maxLength: 2,
select: function (event, ui) {
$("#Some_id2").attr('value', ui.item.extra_value);
}
});
UPDATE aka OPTION 3
From their demo code, if you just want the text value, and don't need the ID (like in your case), just change your source format. Rather than returning a JSON result from the server return an array of strings, or convert the JSON result to a string array, which ever flavor you like
(code from the working sample on their demo page)
var availableTags = ['24', 'about me',... , 'XUIJS'];
$("#searchField").autocomplete({
target: $('#suggestions'),
source: availableTags,
link: 'target.html?term=',
minLength: 1,
matchFromStart: false
});

Use Callback .
$("#searchField").autocomplete(
{
target: $('#suggestions'),
source: myArray ,
link: 'javascript:void();',
minLength:0,
callback: function(e){
var name = $(e.target).attr('name');
//This function will be called when one of the suggestions is clicked according to documentation
window.location = 'target.html?term=' // This line might need some tweaking.
}
});
The code is not tested, you might need to debug this step by step.

If I use
$("#searchField").autocomplete(
{
icon: 'arrow-l',
target: $('#suggestions'),
source: stockArray,
link: 'target.html?term=',
minLength:0,
callback: function(e)
{
var nameq = $(e.currentTarget);
console.log("^^^^^^^^^^^^^^^^^^^^^"+nameq);
//This function will be called when one of the suggestions is clicked according to documentation
window.location = 'target.html?term='
}
});
I get value of nameq as
^^^^^^^^^^^^^^^^^^^^^[object Object] at file:///android_asset/www/index.html:115
and If I use
$("#searchField").autocomplete(
{
icon: 'arrow-l',
target: $('#suggestions'),
source: stockArray,
link: 'target.html?term=',
minLength:0,
callback: function(e){
var nameq = $(e.target).attr('name');
console.log("^^^^^^^^^^^^^^^^^^^^^^^^^^"+nameq);
//This function will be called when one of the suggestions is clicked according to documentation
window.location = 'target.html?term=' // This line might need some tweaking.
}
I get value of nameq as:
^^^^^^^^^^^^^^^^^^^^^^^^^^undefined at file:///android_asset/www/index.html:115

$("#searchField").autocomplete(
{
icon: 'arrow-l',
target: $('#suggestions'),
source: stockArray,
link: 'target.html?term=',
minLength:0,
callback: function(e)
{
var $a = $(e.currentTarget); // access the selected item
console.log("###################!!###"+$a.text());
$('#searchField').val($a.text()); // place the value of the selection into the search box
$("#searchField").autocomplete('clear'); // clear the listview
}
});
Now using $a.text() I get selected item value.

Related

jQuery: Textbox text change event after autocomplete?

I'm using jquery autocomplete plugin for a textbox:
$('#TargetArea').autocomplete({
source: '#Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })'
});
It works fine. Now, I want to do is: when the textbox text changed, call an action to get data from database, then show the data in another div.
$('#TargetArea').change(function () {
var url = "/My/Test";
var target = $("#TargetArea").val();
$.post(url, { Target: target }, function (data) {
$("#resultId").html(data);
});
})
However, this change event never triggered. If I comment out the autocomplete part, then it works fine. Anyone knows what the problem is? or, How I should do this?
Thanks
I think you should use the change event of the autocomplete plugin.
See the documentation here: http://api.jqueryui.com/autocomplete/#event-change
Check it, I think it should works.
$( "#TargetArea" ).autocomplete({
source: '#Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })',
change: function( event, ui ) {}
});
you can make this either
1 - Initialize the autocomplete with the change callback specified:
$( '#TargetArea' ).autocomplete({
source: '#Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })',
change: function( event, ui ) {
var url = "/My/Test";
var target = $("#TargetArea").val();
$.post(url, { Target: target }, function (data) {
$("#resultId").html(data);
});
}
});
or
2- Bind an event listener to the autocompletechange event:
$('#TargetArea').autocomplete({
source: '#Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })'
});
$( '#TargetArea' ).on( "autocompletechange", function( event, ui ) {
var url = "/My/Test";
var target = $("#TargetArea").val();
$.post(url, { Target: target }, function (data) {
$("#resultId").html(data);
});
});
This will be triggered when the field is blurred, if the value has changed.
Source : http://api.jqueryui.com/autocomplete/#event-change

Value isn't passing to function on triggering change event, auto-complete jquery

I made auto complete to a textbox as shown below,
<input type='text' style='width:100px;' id='tags'>
Here is the function which is loading auto complete on page load.
window.onload=function Search_Items() {
var action = "Search";
$.ajax({
method:'GET',
url:'Ajax.php',
data: {action:action},
success:function(result) {
document.getElementById("Search_Result_Div").innerHTML=result;
var temp=document.getElementById("Search_Result").value;
availableProducts=temp.split("`");
$(function() {
var Product=$( "#tags" ).autocomplete({
source: availableProducts,
select: function () {Data_Modification($(this).val());}
});
Product.autocomplete('option','onclick').call(Product);
});
}
});
};
Here i just called a function and passed a value (value is what chosen in auto-complete). But here it's not passing value what i choose instead it's passing what i typed for searching.
What i inferred is, it's calling function and then populate the textbox with value what is chosen. But i need to populate the textbox with chosen value and then call that function.
How do i resolve it? Please if someone got this problem before. Help me out please.
Try this
$(function() {
var Product=$( "#tags" ).autocomplete({
source: availableProducts,
select: function (event, ui) {Data_Modification(ui.item.value);}
});
Product.autocomplete('option','onclick').call(Product);
});
I found a solution myself. I rewrote this
select: function () {Data_Modification($(this).val());}
to
select: function (event,ui) {Data_Modification(ui.item.value);}
and it's works fine.

How do I reference the sepcific object/dom element that an jquery-ui autocomplete function belongs to, when it has been applied to all inputs

$("input[type=text]").autocomplete({
minLength: 3,
source: function (request, response) {
alert( $(this).val() );
I have 3 different input text box's, but $(this).attr("id") or this.id both returned undefined
Not sure what is available inside source regarding this. You can always log it to console to see what is returned. The following pattern is helpful for implementing plugins on many elements
$("input[type=text]").each(function() {
var id = this.id;
$(this).autocomplete({
minLength: 3,
source: function(request, response) {
alert(id);
}
});
});
alert( $(this.element).attr("id") );
works.

JQuery AutoComplete not displaying

I have used JQuery UI autocomplete to cut down on the list of parts I have to display in a drop down, I am also using json to pass the list of parts back but I am failing to see the results, I am sure this is to do with my limited understanding of JQuery's Map function.
I have the following json
{"parts":[{"partNumber":"654356"},{"partNumber":"654348"},{"partNumber":"654355-6"},{"partNumber":"654355"},{"partNumber":"654357"},{"partNumber":"654357-6"},{"partNumber":"654348-6"}]}
which on JSONLint is validated correct
I have viewed the post and response utilising Firebug and seen them to be correct but my auto complete does not seem to display, the closest I have got it to doing so, was when I displayed the entire JSON string with each character having a new line.
here is my JS
$('.partsTextBox').autocomplete({
minLength: 3,
source: function(request, response) {
$.ajax({
url: './PartSearch.ashx',
data: $('.partsTextBox').serialize(),
datatype: 'JSON',
type: 'POST',
success: function(data) {
response($.map(data, function(item) {
return { label: item.partNumber }
}))
}
});
},
select: function(e) {
ptb.value = e;
}
});
Any help anyone can give would be much appreciated. Have edited to include help given by soderslatt
I'm not sure, but shouldn't parts.part be an array ?
http://jsfiddle.net/jfTVL/3/
From the jQuery autocomplete page:
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.
Which means that if you use "value" instead of "partNumber", you should get want you want.
jquery autocomplete plugin format out have to
{"query":"your_query","suggestions":["suggestions_1","suggestions_2"],"data":[your_data]}}
and use autocomplete that
$('#your_input').autocomplete({
minChars: 2
, serviceUrl: './PartSearch.ashx'
, deferRequestBy: 50
, noCache: true
, params: { }
, onSelect: function(value, data) {
}
, ajaxCallBack: function() {
response($.map(data, function(item) {
return { label: item.partNumber}
}))
}
});

Getting the Index of the selected item in jquery auto complete

I am using jQuery autocomplete, as follows:
From my PHP file, I am get json encoded arrays - one for ids and one for names.
I fill the autocomplete with names. In the select function, I am able to correctly alert
the selected item, but I am not able to get the index of the selected item. How do I get it?
$(function() {
$.ajax({
type: "POST",
url: "get_data.php",
success: function(data) {
data_array = jQuery.parseJSON(data);
$("#my_autocomplete").autocomplete({
source: data_array.names,
select: function(event, ui) {
alert(ui.item);
}
});
}
});
});
Example: http://jsfiddle.net/hY5Wt/
Instead of two arrays, you could have one array of objects. Each object would have a label and index: {label:"First", idx:1}. The autocomplete will use the label to display and on select event, you can access ui.item.idx to get the identifier/index.
$( ".selector" ).autocomplete({
source: [{label:"First", idx:1},
{label:"Second", idx:2},
{label:"Third", idx:3}],
select: function(event, ui) { alert(ui.item.idx); }
});
You link to an autocomplete plugin, but your code looks like you are using jQuery UI.

Categories

Resources