jQuery Autocomplete Categories Select Label and Value
Asked Answered
S

3

23

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.

Shinshina answered 16/7, 2011 at 8:28 Comment(0)
P
29

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/

Petta answered 16/7, 2011 at 12:31 Comment(1)
You're welcome. I bumped you up so you should be able to give Andrew a +1 for his focus suggestion. Team effort.Petta
C
26

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/

Cottonweed answered 16/7, 2011 at 12:47 Comment(2)
I have gone with Jen's fix, but have added your suggestion of focus. Thank you for your help.Shinshina
I did return false; on my select: and it worked perfectly. Thank you so much!Lalitta
H
4
$(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);
            }
        });
    });
Horvath answered 24/8, 2012 at 9:37 Comment(1)
Some explanation would have been nice hereKappel

© 2022 - 2024 — McMap. All rights reserved.