jQuery ui autocomplete weird behavior
I have started using jQuery-ui-autocomplete recently. However I am facing a strange and weired behavior. I am try开发者_如何学JAVAing to use autocomplete for multi valued remote data (data from my data service). My code to extract the last term after the comma does not work. My code is as:
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
Code for autocomplete is
$('#txtBox')
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 3,
selectFirst: true,
source: function (request, response) {
$.ajax('My/Data/Source.json', {
global: false,
success: function (data) {
response($.map(data.d.results, function (item) {
return {
label: item.Name,
id: item.id
}
}));
}
});
},
search: function () {
// custom minLength
var term = extractLast(this.value);
if (term.length < 3) {
return false;
}
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
//terms.push("");
this.value = terms.join(", ");
return false;
}
});
When I put a debugger in the function "search", the term is always more than 3. That means it is not correctly evaluating the regular expression. When I include the term
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
it works perfectly. But i cannot include this in my pages. However in firefox this works correctly without doctype declaration also. I tried this in IE8 and IE9 both with no success.
UPDATE After digging a bit further, found that the main issue lies with how IE and other browsers tries to split the last term with regular expression. With IE, when the second time it tried to split the terms after , (comma). Eg http://jsfiddle.net/mE6th/ try to open this link in chrome and IE and see the difference.
If you want the last term in a comma separated string can't you just use this .split(',').pop()
, for example:
'java,c++,php'.split(',').pop();
gives "php"
精彩评论