<select >
<option value="something">something</option>
<option value="something_else">something else</option>
</select>
<input type="text" >
So that when user inputs something, only options with value matching the input will show.
<select >
<option value="something">something</option>
<option value="something_else">something else</option>
</select>
<input type="text" >
So that when user inputs something, only options with value matching the input will show.
using Aaron's answer, this can be the short & easiest solution:
function filterSelectList(selectListId, filterId)
{
var filter = $("#" + filterId).val().toUpperCase();
$("#" + selectListId + " option").each(function(i){
if ($(this).text.toUpperCase().includes(filter))
$(this).css("display", "block");
else
$(this).css("display", "none");
});
};
A much simpler way nowadays is to use the jquery filter() as follows:
var options = $('select option');
var query = $('input').val();
options.filter(function() {
$(this).toggle($(this).val().toLowerCase().indexOf(query) > -1);
});
Just a minor modification to the excellent answer above by Lessan Vaezi. I ran into a situation where I needed to include attributes in my option entries. The original implementation loses any tag attributes. This version of the above answer preserves the option tag attributes:
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(),
attrs: this.attributes, // Preserve attributes.
});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search, "gi");
$.each(options, function(i) {
var option = options[i];
if (option.text.match(regex) !== null) {
var new_option = $('<option>').text(option.text).val(option.value);
if (option.attrs) // Add old element options to new entry
{
$.each(option.attrs, function () {
$(new_option).attr(this.name, this.value);
});
}
$(select).append(new_option);
}
});
});
});
};
Given an input of type text with id #filter_keyword
And a select with id #all_keywords that you have previously populated
$(document).on('input', '#filter_keyword', function(event){
var kw=$(this).val();
$('#all_keywords > option').each(function() {
if ( kw.length > 0 && this.text.replace(kw, '') == this.text )
{
$(this).hide();
} else {
$(this).show();
}
});
});
That's it.
your solution is missing an escape string to use in RegExp for much better use.
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping