RihardsPo
RihardsPo

Reputation: 151

JqueryUI autocomplete input field

I have a situation where I need to change the value of an input field when an autocomplete option has been selected from the dropdown. The problem is that the source for the autocomplete widget consists of objects that have an index and a label. The form that will send the data must take the index but display the label.

HTML:

<input id="input" name="field" type="text">

JS:

values = [
  {label: "aaaaaa", id: 1},
  {label: "aaabbb", id: 2},
  {label: "aaaccc", id: 3},
];

$("#input").autocomplete({
  source: values,
  select: function (event, ui){
    // change #input to ui.item.id
  }
});

(JSFiddle)

When submit the form should contain the index not the label in the input field.

My first thought was changing the input element's value in the select event, which worked in HTML but the submit data did not reflect the change, which made me think that the widget is wrapping the input field and storing the data somewhere else. Also, selecting a value from the autocorrect dropdown does not change the input element's value.

Any ideas?

Upvotes: 0

Views: 3180

Answers (1)

RihardsPo
RihardsPo

Reputation: 151

Seems to work when adding return false to the select function. Cancels the default, which, as the manual mentions, is to replace the text field's value with the value of the selected item.

$("#input").autocomplete({
    source: values,
    select: function (event, ui){
        $("#input").val(ui.item.id);
        return false;
    }
});

(JSFiddle)

This way you could have a hidden field in the form that sends the id, while still displaying the title (value).

A slightly unusual case of RTFM.

Upvotes: 2

Related Questions