Ben Downey
Ben Downey

Reputation: 2665

How to Submit Form When Autocomplete Suggestion Is Chosen

I'm using the jquery-ui autocomplete function I'm not getting what I need. I've got autocomplete working, but right now this is now it behaves.

  1. User starts typing and is given suggestions
  2. User find suggestion needed and presses enter to put suggestion into textbox
  3. User presses "enter" to submit form

I would like to combine what happens in #2 and #3 so that the user makes their selection, presses "enter", and the form submits.

I've found a few posts with similar issues, but I haven't been able to get a solution working for me. I think this should work...but it doesn't.

HTML

    <form accept-charset="UTF-8" action="/contacts" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div>
        <input id="search" name="search" size="30" type="text" />
        <input class="button medium blue1" type="submit" value="Search" />

Javascript

  $(document).ready(function() {
      $("#search").autocomplete({
        source: "/search_suggestions",
        autoFocus: true,
        select: function(event, ui) {
                        $(event.target).val(ui.item.value);
                        $('#search').submit();
                        return false;
                    }
        });
      });

What am I doing wrong?

UPDATE: Thank you, everyone, for the speedy replies!

Upvotes: 2

Views: 3034

Answers (4)

clav
clav

Reputation: 4251

I think you can replace

$('#search').submit();

with

$('#search').parents('form').submit();

Upvotes: 1

PSR
PSR

Reputation: 40318

put id for form as searchFormsIdHere

$(document).ready(function() {
      $("#search").autocomplete({
        source: "/search_suggestions",
        autoFocus: true,
         select: function (event, ui) {
     var selectedObj = ui.item;              
      $("#search").val(selectedObj.value);
     $('#searchFormsIdHere').submit();
        });
      });

Upvotes: 1

Ilia Khokhriakov
Ilia Khokhriakov

Reputation: 3687

You have to specify form id properly:

<form accept-charset="UTF-8" action="/contacts" method="get" id="searchform">
  ...
</form>
$(document).ready(function() {
  $("#search").autocomplete({
    source: "/search_suggestions",
    autoFocus: true,
    select: function(event, ui) {
                    $(event.target).val(ui.item.value);
                    $('#searchform').submit();
                    return false;
                }
    });
  });

Upvotes: 2

epascarello
epascarello

Reputation: 207501

You are trying to run search on a textbox, not the form!

$('#search').closest("form").submit();

or add an id to the form and replace

$('#searchFormsIdHere').submit();

Upvotes: 4

Related Questions