I know I've seen this somewhere, but I can't seem to find the right answer now, and my own knowledge is too fuzzy to get a clear answer on this one.
I have a number of jQuery UI autocompletes applied to a number of fields in a big form.
Instead of using an anonymous function for each of the "source" option function callbacks and "open" event function callbacks, I would like to use one named function that I can re-use for all of the "source" option function callbacks, and another named function that I can re-use for all of the "open" event function callbacks.
My question is, how are these functions to be called?
How are the parameters to be passed back and forth?
How are we to refer to "$(this)" in the named function?
Here is an example:
- <script type="text/javascript">
- var autocompleteOpen = function(event,ui){
- /*--- This function provides no hooks to the results list, so we have to trust the
- selector, for now.
- */
- var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
- var srchTerm = $.trim( $(this).val() ).split(/\s+/).join('|');
- //--- Loop through the results list and highlight the terms.
- resultsList.each(function(){
- var jThis = $(this);
- var regX = new RegExp('(' + srchTerm + ')', "ig");
- var oldTxt = jThis.text();
- jThis.html(oldTxt.replace(regX, '<span class="srchHilite">$1</span>') );
- });
- $(this).autocomplete("widget").css({
- "width": 250
- });
- }
- $(document).ready(function(){
- $('#complex_input').autocomplete({
- source: function(request, response) {
- queryval = $(this).attr('id');
- $.getJSON('/path_to_phpquery/query_autocomplete.php?query='+queryval, request, function(data, status, xhr ) {
- var newmatchArry = new Array();
- var matchArry = data.slice();
- var srchTerms = $.trim(request.term).split(/\s+/);
- //--- For each search term, remove non-matches.
- $.each(srchTerms, function(J, term){
- var regX = new RegExp(term.value, "i");
- matchArry = $.map(matchArry, function(item){
- return regX.test(item) ? item : null;
- });
- });
- response(matchArry);
- });
- },
- open: autocompleteOpen,
- minLength: 0,
- select: function(event, ui) {
- updatedfield( $('input#complex_query').attr('name'),original_field_values );
- },
- sortResults:false
- });
- });
- </script>
What is the correct way to use a named function for the "open" event callback? What is the correct way to capture the "event" and "ui" parameters, and the correct way to refer to "$(this)"?
And how would I go about doing the same for the "source" option function callback?
And how would I go about doing the same for the "select" event function callback?
John R. D'Orazio