Cập nhật câu trả lời của Lessan cũng để giữ các thuộc tính của các tùy chọn.
Đây là lần đầu tiên tôi trả lời trên Stack Overflow vì vậy không chắc tôi có nên chỉnh sửa câu trả lời hay tự tạo câu trả lời hay không.
jQuery.fn.allAttr = function() {
var a, aLength, attributes, map;
if (!this[0]) return null;
if (arguments.length === 0) {
map = {};
attributes = this[0].attributes;
aLength = attributes.length;
for (a = 0; a < aLength; a++) {
map[attributes[a].name.toLowerCase()] = attributes[a].value;
}
return map;
} else {
for (var propin arguments[0]) {
$(this[0]).attr(prop, arguments[0][prop]);
}
return this[0];
}
};
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({ value: $(this).val(),
text: $(this).text(),
allAttr: $(this).allAttr() });
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var search = $.trim($(this).val());
var regex = new RegExp(search, "gi");
$.each($(select).empty().data('options'), function(i, option) {
if (option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text)
.val(option.value)
.allAttr(option.allAttr)
);
}
});
});
});
};
Tôi đã cố gắng để thực hiện điều này nhưng nó có thể không được trình duyệt chéo tương thích http://stackoverflow.com/questions/1271503/hide-options-in-a-select-list-using-jquery – James