Optimize jQuery code includes autocomplete function for different input box with different autocomplete content I have this code below for autocomplete feature of several inputTextbox. The input box also share same class".wikiInput". When user typed something in either of them, a relevant autocomplete dropdown box should show up. Instead of hard code one by one. How do I optimize them into a simpler format. Note the lookup has different arrays.

(function () {
    var cdTeamInput = $("#ctl00_ContentPlaceHolder1_txtAssociation");
    if (cdTeamInput.length &gt; 0) {
        cdTeamInput.autocomplete({
            deferRequestBy: 0,
            autoSelectFirst: true,
            lookup: txtAssociation,
            onSelect: function (value, data) {
                cdTeamInput.val(value.value);
                $(".wikiSubmit").click();
            }
        });
    }
})();

(function () {
    var cdSubjectInput = $("#ctl00_ContentPlaceHolder1_txtSubject");
    if (cdSubjectInput.length &gt; 0) {
        cdSubjectInput.autocomplete({
            deferRequestBy: 0,
            autoSelectFirst: true,
            lookup: txtSubject,
            onSelect: function (value, data) {
                cdSubjectInput.val(value.value);
                $(".wikiSubmit").click();
            }
        });
    }
})();


Update: I really like user2734550's first answer. however, the lookup array will be undefined in cross page situation. Like one of the page have only one lookup array but don't have others. so js file would be broken. How do I avoid this problem? Seems like if lookup.length > 0 statement doesn't work.
Quick answer: Use arguments.

function initAutocomplete(selector, lookup) {
  $(selector).autocomplete({
    deferRequestBy: 0,
    autoSelectFirst: true,
    lookup: lookup,
    onSelect: function (value, data) {
      cdSubjectInput.val(value.value);
      $(".wikiSubmit").click();
    }
  });
}

initAutocomplete("#ctl00_ContentPlaceHolder1_txtAssociation", txtAssociation);
initAutocomplete("#ctl00_ContentPlaceHolder1_txtSubject", txtSubject);


Of course, it might be nice to decouple the markup and the code some more. Depending on how the lookup lists (their length and contents), you could do something like this in your HTML:

&lt;input data-lookup="foo,bar,baz" ...&gt;


and init every autocompleting input on the page in one go with:

$("input[data-lookup]").each(function () {
  var input = $(this),
      lookup = input.data("lookup").split(","); // get the lookup strings

  input.autocomplete({
    deferRequestBy: 0,
    autoSelectFirst: true,
    lookup: lookup,
    onSelect: function (value, data) {
      cdSubjectInput.val(value.value);
      $(".wikiSubmit").click();
    }
  });
});