Martin Erlic
Martin Erlic

Reputation: 5665

Cannot pass autocomplete selection value to input field

I'm trying to add the value of my autocomplete selection to a specific input field with id initialNameField.

Autocomplete:

<div class="ui-widget">
   <label for="tags">Search: </label>
   <input class="tags" />
</div>

Input:

<input type="text" th:field="*{selectedInitialName}" class="initialNameField" id="initialNameField"
   name="initialName"/>

Includes:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Autocomplete Script:

<script type="text/javascript">
        //<![CDATA[
        $(function() {
            var availableTags = [
                "1",
                "2",
                "3",
                "4",
            ];
            $(".tags").autocomplete({
                source: availableTags,
                minLength: 1,
                dataType: 'json',
                select: function(event, ui) {
                    $('#initialNameField').val(ui.item.id);
                }
            });
        });
        //]]>
    </script>

What should I be doing to make this work?

Upvotes: 0

Views: 169

Answers (2)

selvarajmas
selvarajmas

Reputation: 1643

Try to use ui.item.label when you setting selected text to textbox.

$(document).ready(function () {
  var availableTags = [
    "1",
    "2",
    "3",
    "4",
  ];
  $(".tags").autocomplete({
    source: availableTags,
    minLength: 1,
    dataType: 'json',
    select: function(event, ui) {
      $('#initialNameField').val(ui.item.label); // input the selected text
    }
  });
});

Here is the sample working code : http://jsfiddle.net/32Bck/625/

Upvotes: 1

Dan Cantir
Dan Cantir

Reputation: 2955

You have to set the value like this:

$('#initialNameField').val(ui.item.value); // Or ui.item.label

Because ui is a object like: {"item":{"label":"1","value":"1"}}

Working fiddle here: https://jsfiddle.net/wc0rtpa9/

Upvotes: 1

Related Questions