Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 596
chrisk Avatar asked Jul 16 '11 08:07

chrisk


3 Answers

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/

like image 55
jk. Avatar answered Feb 12 '23 07:02

jk.


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/

like image 32
Andrew Whitaker Avatar answered Feb 12 '23 05:02

Andrew Whitaker


$(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);
            }
        });
    });
like image 27
Ismael Miguel Avatar answered Feb 12 '23 05:02

Ismael Miguel