jquery autocomplete xml search from beginning
Search autocomplete using xml as source with search from beginning
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/start/jquery-ui.css">
<h1>jQuery Autocomplete XML Source Search from Beginning</h2>
<p class="ui-widget">Try typing 'Lo' it will match on 'London'. <br />Try typing 'don', no matches.<br />Try typing 'the', matches 'The Tower of London'. You get the idea.</p>
<div class="ui-widget">
<label for="test">London matches: </label>
<input id="test" />
</div>
<p id="result" class="ui-widget red"></p>
JavaScript
//for fiddle demo xml had to be loaded in this way
//use your own ajax call for your page
$.ajax({
url: "/echo/xml/", //your url
type: "POST", //may not need this-fiddle did-default is GET
dataType: "xml",
data: {
xml: "<geonames><geoname><name>London</name><geonameId>2643743</geonameId><countryCode>GB</countryCode><countryName>United Kingdom</countryName></geoname><geoname><name>London</name><geonameId>6058560</geonameId><countryCode>CA</countryCode><countryName>Canada</countryName></geoname><geoname><name>The Tower of London</name><geonameId>6286786</geonameId><countryCode>GB</countryCode><countryName>United Kingdom</countryName></geoname></geonames>"
}, //should not need to define 'data' on your own xml call
success: function(xmlResponse) {
var data = $("geoname", xmlResponse).map(function() {
return {
value: $("name", this).text() + ", " + ($.trim($("countryName", this).text()) || "(unknown country)"),
id: $("geonameId", this).text()
};
}).get();
$("#test").autocomplete({
source: function(req, response) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function(item) {
return matcher.test(item.value);
}));
},
minLength: 2,
select: function(event, ui) {
$("p#result").html(ui.item ? "Selected: " + ui.item.value + ", geonameId: " + ui.item.id : "Nothing selected, input was " + this.value);
}
});
}
});