1

I wrote some auto complete code who works, the list is showing up, but now I need to make those clickable, I have an ID stored in the JSON who I call over ajax, but I can't get it in the 'select' section from the autocomplete, so I declared an array and filled it with the IDs in the 'source' mapping section. But I need to know the index number of the clicked/selected suggestion.

Here is my code:

// Declarations
var i   = 0;
var j   = 0;
var ids = []; // Array of ids

$('#search-bar').autocomplete(
{
    source : function(requete, reponse){
    $.ajax(
    {
            url : 'search/' + $('#search-bar').val(), // JSON source 
            dataType : 'json',
            success : function(data){
                reponse($.map(data, function(objet)
                {
                    ids[i] = objet.id;  // Filling up the array
                    i++;
                    return objet.name;
                }));
            }
        });
    },
    select: function (event, ui)
    {
        window.location = 'project/' + ids[j];  // Link the the project page
        j++;    // not working
    }
});

Here is an example of returned JSON:

[{"id":1,"name":"Project 1"},{"id":2,"name":"Project 2"}]

Someone knows how to replace my 'j' variable with the index of the clicked/selected entry ?

0

1 Answer 1

1

You should return an object in the source method, then in the select method use the id of the selected item to construct the url:

$('#search-bar').autocomplete(
{
    source : function(requete, reponse){
    $.ajax(
    {
            url : 'search/' + $('#search-bar').val(), // JSON source 
            dataType : 'json',
            success : function(data){
                reponse($.map(data, function(objet){
                    return {
                        label: objet.name,
                        value: objet.id,
                       id: objet.id
                    };
                }));
            }
        });
    },
    select: function (event, ui)
    {
        window.location = 'project/' + ui.item.id;
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

the idea is that response method can return a more complete object that contains also the ID of the item
What do I need to return then ? Because with your code it says me syntax error on line value: objet.id,
sorry, I've missed a return

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.