问题
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