user2920430
user2920430

Reputation: 13

Return value of a JQuery autocomplete using an array of objects as its source

In a JQuery autocomplete which uses an array of objects as its source, can I display the label in the INPUT and later access the value? The default behavior is that the value is displayed in the INPUT after selection. In this case the values represent indexes to unique keys in rows in a table.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>autocomplete demo</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>
    <label for="autocomplete">Select a programming language: </label>
    <input id="autocomplete">
    <script>
    $( "#autocomplete" ).autocomplete({
      source: [ { label:"c++", value:1 }, { label: "java", value:2 }, { label: "javascript", value:3 } ]
    });
    </script>
</body>
</html>

Upvotes: 1

Views: 7824

Answers (1)

Edward Lee
Edward Lee

Reputation: 951

Set val of the input by selected label to display the label instead of its value

$( "#autocomplete" ).val( ui.item.label );

Add data attribute on the input

<input id="autocomplete" data-value>

and store selected value

$( "#autocomplete" ).attr("data-value",ui.item.value);

Here is JSFiddle

Upvotes: 1

Related Questions