user1740375
user1740375

Reputation:

Jquery UI Autocomplete - how to add another value with the item?

I am using the autocomplete and I fetch items from the database. Here is my JS:

    $(".add").autocomplete({

        source: function(req, add){

            $.getJSON("add.php?callback=?", req, function(data) {

                var suggestions = [];

                $.each(data, function(i, val){
                    suggestions.push(val.name);
                });

                add(suggestions);
        });
    },

        messages: {
            noResults: '',
            results: function() {}
        }

    });

I am sending an array with PHP where there is 'name' and 'id'. I want to be able to know to ID of the selected item when the user selects it without going to the database, but I can't put it in the source without it being displayed, which is what I don't want. What I want to have an inivisible ID with every item autocomplete finds and when the user selects it and submits the value, I can insert the object in the database.

Here is my PHP file:

<?php

require('connect.php');

$param = $_GET["term"];

$query = mysqli_query($connection, "SELECT * FROM stuff WHERE name REGEXP '^$param'");

for ($x = 0, $numrows = $query->num_rows; $x < $numrows; $x++) {
    $row = mysqli_fetch_assoc($query);
    $add[$x] = array("name" => $row["name"], "id" => $row["id"]);
}

$response = $_GET["callback"] . "(" . json_encode($add) . ")";
echo $response;

Hope this makes sense.

Upvotes: 1

Views: 5140

Answers (1)

Maverick
Maverick

Reputation: 478

You could take example from this link: http://jqueryui.com/autocomplete/#custom-data

$("#txtItem").autocomplete({    
    select: function (event, ui) {
               return false;
            }
}).data("ui-autocomplete")._renderItem = function( ul, item ) {
        return $("<li>")
        .append( "<a onclick='itemclicked(this)' id='" + item.id + "'>" + item.desc + "</a>" ).appendTo( ul );
        };

function itemclicked(sender)
{
    alert($(source).attr("id");)
}

Upvotes: 2

Related Questions