0
votes

I have a textfield with autoselect in Jquery, when you type three letters you get a query from the database and display some data. I need to get the id property from the _renderItem method, but I'm not getting it correctly. Below is the code that I have:

    $("#textField").autocomplete({
    minLength: 3,
    source: function(request, response) {
        var loadIdentities = "<?php echo $this->Html->url(array('controller' => 'Identities', 'action' => 'getIdentity')); ?>/" + Base64.encode(request.term);
        $.getJSON(loadIdentities, function(data) {
            response(data);
        });
    }
}).data("ui-autocomplete")._renderItem = function(ul, item) {        
     console.log(item.id);
     return $("<li>")           
        .append("<a>" + item.label + "</a>")
            .appendTo(ul);
};

In the line console.log(item.id) I'm not getting the correct value. This happens when you select with a mouse click the element from the autocomplete list, when you click the item.id is not updated correctly, and the value that is displayed instead the correct item.id is the one that you have when you are typing for the autocomplete.

For example, if in the text field you type the name "John Smith", you will get two options on the autocomplete: John Smith and John Smithson. If you select with a click the "John Smithson" option, you will have the item.id value of "John Smith", and I want to have the id of "John Smithson"

How can I solve this problem?

1

1 Answers

0
votes

I was able to solve this using the select method of autocomplete:

    select: function( event, ui ) {
            $("[name='elementName[0]']").val(ui.item.label);
            $("[name='elementID[0]']").val(ui.item.id);
            return false;
    }

I put that after source and now it works.