开发者

How to remove an autocomplete once added to an element?

After I add a autocomplete to an element like:

commObj=$("#communityName").autocomplete("auto_commNam开发者_JAVA技巧e_backend.php",
                {'onItemSelect': handleItemSelect}, {'extraParams': 'ndo' + ndo});

Is there a way I could disable it or remove the autocomplete for the element dynamically?

I am using modified jquery autocomplete plugin from Dylan Verheul. http://www.pengoworks.com/workshop/jquery/autocomplete_docs.txt


You can remove the autocomplete behaviour by using following line of code:

if (jQuery(control).data('autocomplete')) {
  jQuery(control).autocomplete("destroy");
  jQuery(control).removeData('autocomplete');
}


The easiest and safest way I found is:

$(control).autocomplete({source: []});

Alternatively, as mentioned before this also works:

$(control).autocomplete("destroy");

If you are sure your control has an autocomplete handler set.


In the latest version of jQuery UI(1.12), $(control).data('autocomplete') isn't returning true even when the autocomplete data is present.

Instead, a check for the presence of ui-autocomplete-input class returned true.

The following should suffice, I believe.

if ($(control).hasClass('ui-autocomplete-input')) {
   $(control).autocomplete("destroy");
}


If you add a class like, say "EnableAC" to your element, you could target that class for autocomplete. When you complete the autocomplete and want to disable it, you remove that class.

Why would do you want to disable the feature though? It may confuse your users if they want to change their selection and the autocomplete doesn't fire.


I've just had a brief look at the js file for the plugin.

There appears to be a javascript line (number 21) during the initialisation of the jquery.autocomplete.js plugin that sets up the originating source input as:

input.autocompleter = me;

Without testing, maybe you could simply then call the following to remove the link between the plugin and the original input?

$('#<your input id>').autocompleter = null;


That plugin wires itself up to the <input> pretty tightly. If it were my page, I think I'd just have two tags with the same "name", one with autocomplete and one without. When I wanted to toggle between them, I'd make one disabled and hidden, and enable/show the other. (edit oh and also make sure the values of the fields get copied back and forth when they switch)


I just tried $('#').autocomplete = null; and it works. I was allowing name change of the fly and the result wouldnt show, now it does. The old unchanged name would show before now the new one does


Disable autocomplete by element ID:

 $("#elementId").autocomplete({
  disabled: true
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜