How to create generic (reusable) JavaScript autocomplete function

后端 未结 2 1524
[愿得一人]
[愿得一人] 2021-01-15 09:53

I now have a working JavaScript autocomplete function, thanks to help from many of you. Now I want to make the function reusable. There are three variables that need to be s

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-15 10:31

    It looks like you're using jQuery, so you might want to implement it as a plugin.

    (function($) {
      $.fn.bobsAutocomplete = function(resultFieldName, lookupURL) {
        this.autocomplete({
          source: function(request, response) {
              $.ajax({
                  type: "POST",
                  url: lookupURL,
                  contentType: 'application/json',
                  dataType: "json",
                  data: JSON.stringify({prefixText: request.term, count: 20}),
                  success: function(data) {
                      var output = jQuery.parseJSON(data.d);
                      response($.map(output, function(item) {
                          return {
                              label: item.Label + "(" + item.Value+ ")",
                              value: item.Value
                          }
                      }));
                  },
                  error: function(XMLHttpRequest, textStatus, errorThrown) {
                      alert(textStatus);
                  }
              });
          },
          minLength: 2,
          select: function(event, ui) {
              $('#' + resultFieldName).val(ui.item.value);
              return ui.item.label;
          }
        });
        return this;
      };
    })(jQuery);
    

    Usage:

    $("#dotmatch").bobsAutocomplete("dotnumber", "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList");
    

提交回复
热议问题