Richard Banks
Richard Banks

Reputation: 2983

Getting the selected value of jQuery autocomplete

I have a form and it can have multiple jQuery autocompletes. When the form is submitted I want to get the selected values in the autocompletes, dump the values into a hidden text field and submit to the server.

I can't seem to find any info on how to do this. My code is below which works fine and binds to all textfields with the class autocomplete. Any ideas on this?

$(".autocomplete").autocomplete({
            autoFocus: true,
            source: function(request, response) {
                $.ajax({
                    url: "@Url.Action("SearchEmployees", "ProjectBase")",
                    minLength: 3,
                    dataType: "json",
                    type: "GET",
                    data: { term: request.term },
                    success: function(data) {
                        response($.map(data, function(item) {
                            return {
                                label: item.Fullname,
                                value: item.EmployeeId
                            };
                        }));
                    },
                    error: function(xhr, textStatus, errorThrown) {
                        alert("error: " + errorThrown);
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();
                $(this).val(ui.item.label);
            },
            change: function (event, ui) {
                alert("change: " + (ui.item ? ui.item.label : "<no item>"));
            }
        });

Upvotes: 0

Views: 5040

Answers (1)

guest271314
guest271314

Reputation: 1

You can use submit event, .each() to iterate .autocomplete elements, FormData .append() to append .autocomplete("instance").selectedItem .label, .value to FormData object; $.post() FormData object to server. See instance()

$("form").on("submit", function(e) {
  e.preventDefault();
  var data = new FormData();
  $(".autocomplete").each(function(index, selected) {
    var curr = $(this).autocomplete("instance").selectedItem;
    data.append(curr.label, curr.value);
  });
  $.post("/path/to/server", data);
})

Upvotes: 1

Related Questions