Getting the Index of the selected item in jquery auto complete - javascript

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.

Related

JQuery .each() Function assigning the same ID for children elements (not iterating?)

I am trying to iterate through a list of children elements and pass their encrypted IDs via AJAX to my controller to update display order on drop using jQuery Sortable. jQuery is selecting the correct amount of child elements but it is assigning the same ID from the dragged and dropped item to both items in my array. I'm not sure what's going on.. I would really appreciate the help! Thanks
JS Code:
$(document).ready(function () {
$(".reqconsentList").sortable({
axis: 'y',
update: function (event, ui) {
var consentForms = [];
$(this).children().each(function (index) {
consentForms.push({ 'id': $('#ConsentID').val(), 'position': index + 1 });
});
var data = { 'sortedConsentForms': consentForms };
//debugger;
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '#Url.Action("UpdateConsentDisplayOrder", "Check", new { Area = "Administration" })'
});
}
});
});
First problem is that $('#ConsentID').val() would return the value from the first element with that id. ID needs to be Unique.
Changing the jquery to class would be correct, but the code would still not know what "element" it should get the data from.
So we need to tell it search for the .reqconsentList, to look for child with the class .ConsentID
This is done this way: $(this).find('.ConsentID').val()

JQuery-ui-autocomplete shows value in textbox

I am using jquery-ui-1.11.4 and autocomplete. My source is obtained by ajax which is properly returning this type of JSON
[
{"label":"foo", "value":"01-1013"},
{"label":"bar", "value":"01-1003"}
]
When I scroll down to select my choice everything works correctly. The value is added to printTag and the label is added to the text box (inputTag). The problem is that as I use the down arrow to select my choice, the value is displayed in the text box, not the label. The label is ONLY displayed in after I select my choice.
I read a couple of reviews and have tried to modify my code but I can't figure it out. Here is my autocomplete.
$(inputTag).autocomplete({
source: function(request, response) {
$.ajax({
url: myAjaxFile,
method: "GET",
dataType: "JSON",
data: getData+'='+ request.term,
success: function(data){
response(data)
}
});
},
focus: function(event, ui){
event.preventDefault();
$(inputTag).val(ui.item.label);
return false;
},
select: function(event, ui) {
$(printTag).val(ui.item.value);
// prevent autocomplete from updating the textbox
event.preventDefault();
$(inputTag).val(ui.item.label);
return false;
},
minLength: 2
});
How do I display the label in the text box rather than the value?

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.

get name of list item click in autocomplete in jquery

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.

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}
}))
}
});

Categories

Resources