jquery ui autocomplete change event

╄→尐↘猪︶ㄣ 提交于 2019-12-12 01:54:57

问题


I'm trying to make Jquery autocomplete to only allow selection items. i used the change event to detect that:

 change: function (event, ui) {
            if (ui.item) {
                $(this).val('');
            }
        }

and it works great in IE. but in chrome ui.item in allways null even if the item was selected from list.

then i tried a different approach. and check the event type instead:

 if (event.originalEvent.type != "autocompletechange") {
            $(this).val('');
        }

and it works great in Chrome but in IE the event is 'Blur'.

is there a solution that fits both browsers??

thanks, Yuval.


回答1:


I had the same problem and had to work around it. There doesn't seem to be a fix to this.

jQuery's autocomplete sends event and ui objects only on the select event. On change event no object is sent, unfortunately.

This is what I did and it seems to be working smooth:

$('#autocomplete-input').autocomplete({ 
    source : fields, // fields is an array of objects with field_name and field_id

    change : function() {

        var input = $('#autocomplete-input').val().trim();

        if ( input.length > 0 ) {

            var field_found = false;
            $.each( fields, function( index, value ) {
                if ( input == fields[index]['field_name'] )
                    field_found = fields[index]['field_id'];
            });

            if ( field_found ) {

                $('#field-selected-hidden').val( field_found ); 
            } else {

                $('#field-selected-hidden').val('');
            }

        } else {

            $('#field-selected-hidden').val('');
        }
    }
});

What it basically does is: if the input field changes value, it searches the array of the pre-set autocomplete fields (the source). If it has the a value equal to what the new field value has changed to, it sets the hidden form field to the id of the field (or whatever field you want to capture.)

Hope it helps...



来源:https://stackoverflow.com/questions/28020466/jquery-ui-autocomplete-change-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!