Best way to reuse autocomplete with the same target

Best way to reuse autocomplete with the same target

Hello all,

I am currently working on a project where I am using a few autocompletes with the same targets in multiple places. Instead of copying/pasting code I would, naturally, rather have the code in one place and call a function that turns the target textbox into an autocomplete. Here is an example of what I am doing, this gets populates an autocomplete with school names :

  1.         //Turn the school text field into an autocomplete
  2.         $("#school_text").autocomplete({
  3.             source:function(req,add){
  4.                
  5.                 //Set the source of this to the degrees_json php
  6.                 $.getJSON('schools_json.php',req,function(data){
  7.                
  8.                     //create array for response objects 
  9.                     var suggestions = [];
  10.                    
  11.                     //process response 
  12.                     $.each(data, function(i, val){ 
  13.                         suggestions.push(val.name); 
  14.                
  15.                     });
  16.                     add(suggestions);
  17.                
  18.                 });
  19.             },
  20.             minLength: 2
  21.            
  22.         });   
Now one way I could do this would be to make a function that takes in a textbox as a parameter and link that in every page I want to use it, like :

  1. function schoolAuto(textbox)
  2. {
  3.         //Turn the school text field into an autocomplete
  4.         $("textbox").autocomplete({
  5.             source:function(req,add){
  6.                
  7.                 //Set the source of this to the degrees_json php
  8.                 $.getJSON('schools_json.php',req,function(data){
  9.                
  10.                     //create array for response objects 
  11.                     var suggestions = [];
  12.                    
  13.                     //process response 
  14.                     $.each(data, function(i, val){ 
  15.                         suggestions.push(val.name); 
  16.                
  17.                     });
  18.                     add(suggestions);
  19.                
  20.                 });
  21.             },
  22.             minLength: 2
  23.            
  24.         }); 
  25. }
Since I am basically creating the same few autocompletes over and over I could just make a function for each. My question is, is this the way I should be doing it? Is there a better way? If so why is it better? I'm still pretty new to jQuery and am not really familiar with best practices. I'm fairly well versed in OOP(although haven't done much with Java Script) so I thought of creating a class but don't really know if that is necessary. Could anyone give me some advice? I would really appreciate it, thanks much!