chrisk
chrisk

Reputation: 342

jQuery Autocomplete Categories Select Label and Value

Trying to get the jQuery Autocomplete with categories to return the selected value to the search field and the value to a separate input field.

I have modified the data to have a value as well as label and category.

See http://jsfiddle.net/chrisk/bM7ck/

But the value is always returned to the search field instead of the label.

Upvotes: 23

Views: 67203

Answers (3)

Ismael Miguel
Ismael Miguel

Reputation: 41

$(function() {
        $( "#searchitems" ).autocomplete({
            source: [<?php echo $search /*example for full list in php*/?>],
            minLength: 2,
            select: function(event, ui) {
                event.preventDefault();
                $("#searchitems").val(ui.item.label);
                $('#searchitemvalue').val(ui.item.value);
                window.location="#"; //location to go when you select an item
            },
            focus: function(event, ui) {
                event.preventDefault();
                $("#searchitems").val(ui.item.label);
                $('#searchitemsvalue').val(ui.item.value);
            }
        });
    });

Upvotes: 4

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

You're close, you just need to:

  1. Add return false to the end of your select event handler, and
  2. Add an event handler for the focus event so that you can override that as well, using the label instead of the value.

Here's your code updated:

$("#search").catcomplete({
    delay: 0,
    source: data,
    select: function(event, ui) {
        $('#search').val(ui.item.label);
        $('#searchval').val(ui.item.value);
        return false; // Prevent the widget from inserting the value.
    },
    focus: function(event, ui) {
        $("#search").val(ui.item.label);
        return false; // Prevent the widget from inserting the value.
    }
});

Here's an updated example: http://jsfiddle.net/q2kDU/

Upvotes: 26

jk.
jk.

Reputation: 14435

That's how the jquery ui autocomplete works when you supply both a label and a value. If you want the label returned to the search field, then rename the value field.

Updated fiddle: http://jsfiddle.net/jensbits/bM7ck/3/

Upvotes: 29

Related Questions