Jquery UI autocomplete - Unwanted triggering due t

2020-08-04 06:58发布

问题:

I have a few autocomplete's in my application. Some of them get populated from a database when loading. If the input value contains special characters like æøå, autocomplete triggers a search even if I the user haven't been anywhere near the html input. This only applies to Internet Explorer 11 (and possibly lower). In FF and Chrome it works as you would expect.

Consider the following input:

<input type='text' class'ac' value='chars æøå' />

If applying an autocomplete to this input where one of the possible search results is the same as the default value ('chars æøå'), the search will trigger on initialisation.

JSfiddle here (use IE to see it trigger on load): http://jsfiddle.net/BY9gU/

I would LOVE to just disregard IE, but unfortunately some of my customers still use it...

Any ideas for a workaround?

回答1:

I had this problem a while ago, and I ended up doing the following in my html:

<input type='text' class'ac' data-value='chars æøå' />

And in my autocomplete initialization I have:

   $("input").autocomplete({
        source: availableTags, 
        create: function(event, ui) {
            $(this).val(($(this).attr("data-value"))); 
        }
    });

Looks like this only happens if the value-attribute contains sspecial characters.



回答2:

Try to add this code in the head of the document:

<meta http-equiv='X-UA-Compatible' content='IE=Edge'>


回答3:

I have the same problem, but haven't found a fix (yet).

It's a problem that is IE-related and not jQuery, according to the jQueryUI bugs forum. And they don't have an answer and it's not sure they will be able to do something about this issue.

http://bugs.jqueryui.com/ticket/9796#no1



回答4:

As @cverb states in his answer, this is an IE problem and can't be blamed on jQuery UI. However, I've made a workaround which seems to work fine, at least in my project:

Locate this code in jquery ui source:

search: function( value, event ) {
    value = value != null ? value : this._value();

    // always save the actual value, not the one passed as an argument
    this.term = this._value();

    if ( value.length < this.options.minLength ) {
        return this.close( event );
    }

Change it to this (add the if-block):

search: function( value, event ) {
    value = value != null ? value : this._value();

    // The following if-block is inserted by me as a workaround.
    // Add all characters which may cause you trouble in the
    // regex pattern.
    if ( this._value().match(/[æøåÆØÅ]/) && this.term === undefined ) {
        return;
    }

    // always save the actual value, not the one passed as an argument
    this.term = this._value();

    if ( value.length < this.options.minLength ) {
        return this.close( event );
    }

Voila! It works. I can't guarantee that I haven't broken some other functionality, but I'm 99,9% sure that I haven't :)