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.

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. I bumped you up so you should be able to give Andrew a +1 for his focus suggestion. Team effort.
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/

2 Comments

I have gone with Jen's fix, but have added your suggestion of focus. Thank you for your help.
I did return false; on my select: and it worked perfectly. Thank you so much!
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);
            }
        });
    });

1 Comment

Some explanation would have been nice here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.