Created
August 4, 2010 11:04
-
-
Save jarrettmeyer/507972 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// jQuery UI combobox | |
// Based on the combobox example on the jQuery UI home page. | |
// Must load both jQuery and jQuery UI Widgets before loading this document. | |
// I use CSS to position the button inside the input element, so it looks just | |
// like a drop down box. | |
// | |
$.widget("ui.combobox", { | |
_create: function () { | |
var self = this; | |
// hide the original select box. | |
var id = this.element[0].id; | |
var name = this.element[0].name; | |
var select = this.element.hide(); | |
this.element.removeAttr("name"); | |
this.element.removeAttr("id"); | |
// create a hidden element to store the selected id. | |
var hidden = $("<input type=\"hidden\" name=\"" + name + "\" id=\"" + id + "\" value=\"\" />") | |
.insertAfter(select); | |
// create a text element that will be our autocomplete. | |
var input = $("<input type=\"text\" />") | |
.insertAfter(select) | |
.attr("id", "combobox-for-" + id) | |
.autocomplete({ | |
source: function (request, response) { | |
var matcher = new RegExp(request.term, "i"); | |
response(select.children("option").map(function () { | |
var text = $(this).text(); | |
if (this.value && (!request.term || matcher.test(text))) return { | |
id: this.value, | |
label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"), | |
value: text | |
}; | |
})); | |
}, | |
delay: 0, | |
change: function (event, ui) { | |
if (!ui.item) { | |
// remove invalid value, as it didn't match anything | |
$(this).val(""); | |
return false; | |
} | |
select.val(ui.item.id); | |
self._trigger("selected", event, { | |
item: select.find("[value='" + ui.item.id + "']") | |
}); | |
}, | |
select: function (event, ui) { | |
$("#" + id).val(ui.item.id); | |
}, | |
minLength: 0 | |
}) | |
// add a button to the form. | |
$("<button> </button>") | |
.attr("tabIndex", -1) | |
.attr("title", "Show All Items") | |
.addClass("combobox-button") | |
.insertAfter(input) | |
.click(function () { | |
// close if already visible | |
if (input.autocomplete("widget").is(":visible")) { | |
input.autocomplete("close"); | |
return; | |
} | |
// pass empty string as value to search for, displaying all results | |
input.autocomplete("search", ""); | |
input.focus(); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment