Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery autocomplete links

I use jquery's autocomplete on my site. Right now the menu it produces has links that you can click.

However, when you click them they simply go into the text field. I would like to be able to click on the link (or press enter) and be taken to another page, specifically change the URL's get variable.

To make this a little more complicated, each item in the drop down is assigned an ID by my mysql database. The link that each item should go to is index.php?id=$id where $id is its ID from the database.

Since I have hundreds of items in the menu, how can I alter the current code to include links that redirect to index.php?id=$id getting $id from my database?

CODE: standard code from http://jqueryui.com/demos/autocomplete/

<script>
$(function() {
    var availableTags = [
        <?php
        include 'connect.php';

        $result=mysql_query("SELECT * FROM searchengine");

        while ($row=mysql_fetch_assoc($result)){

        $title=$row['title'];
        $id=$row['id'];

        echo "\"$title\",";

        }


        ?>
    ];
    $( "#tags" ).autocomplete({
        source: availableTags

    });

});
</script>

P.S. I use php inside the jquery to generate a list of variables.

like image 512
user780483 Avatar asked Jul 03 '26 22:07

user780483


1 Answers

Since I don't know PHP, I can't help you with the server-side code, but it should be easy enough to figure out once you understand the different data that autocomplete can use.

For the widget's data source, you can specify an array of objects with a label and value property. You could leverage the value property to store the id from your database, and then define an event handler for the select event to send the user to the correct page.

Here's an example:

$("input").autocomplete({
    source: [
        { label: "Home", value: '3' },
        { label: "Admin", value: '4' },
        { label: "Search", value: '55' }
    ],
    select: function(event, ui) {
        /* Prevent the input from being populated: */
        event.preventDefault();
        /* Use ui.item.value to access the id */
        window.location.href = "/index.php?id=" + ui.item.value;
    }
});

Here's a working (simpler) example: http://jsfiddle.net/j2JUb/

As a side note, I would consider using the remote datasource option that autocomplete provides if you have a ton of possible results.

like image 125
Andrew Whitaker Avatar answered Jul 06 '26 13:07

Andrew Whitaker