jqueryjquery-pluginsjquery-autocompleteautosuggest

jQuery Autocomplete using extraParams to pass additional GET variables


I am referring specifically to the jQuery Autocomplete v1.1 plugin by Jörn Zaefferer [source: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/] as there seems to be quite a few variations of this plugin.

I'm trying to pass additional parameters to the server when the user starts typing because I have multiple fields that I want autocomplete to provide suggestions for.

In addition to the query, I want to send the input name attribute to the server but I can't seem to use $(this).attr('name') within the extraParams.

My jQuery:

   $('.ajax-auto input').autocomplete('search.php', {
     extraParams: {
      search_type: function(){
       return $(this).attr('name');
      }
     }
   })

This is my HTML.

 <form method="post" action="#" id="update-form" autocomplete="off">
  <ol>
         <li class="ajax-auto">
             <label for="form-initials">Initials</label>
                <input type="text" id="form-initials" name="initials" />
            </li>
         <li class="ajax-auto">
             <label for="form-company">Company</label>
                <input type="text" id="form-company" name="company" />
            </li>
  </ol>
 </form>

Any suggestions?


Solution

  • I am using the autocomplete function that is now part of jQuery UI. Passing an 'extraParams' field does not work but you can just append the values in the request query string.

    $(document).ready(function() {
        src = 'http://example.com/index.php';
    
        // Load the cities straight from the server, passing the country as an extra param
        $("#city_id").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: src,
                    dataType: "json",
                    data: {
                        term : request.term,
                        country_id : $("#country_id").val()
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },
            min_length: 3,
            delay: 300
        });
    });