我有以下视图列出水果,我可以按输入文本值
过滤这是
的代码段@Html.TextBoxFor(m => m.SearchKey, new {@id ="SearchKey" })
@Html.ListBox("L", new MultiSelectList(Model.FruitList, "Id", "Name"), new { multiple = "multiple", id = "FruitList" })
这里的过滤方案我使用了以下两个选项。
选项1
$(function() {
$('#FruitList').filterByText($('#SearchKey'), true);
});
jQuery.fn.filterByText = function (textbox, selectSingleMatch) {
return this.each(function ()
{
var select = this;
var options = [];
$(select).find('option').each(function()
{
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function()
{
var options = $(select).empty().scrollTop(0).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)
{
$(select).append($('<option>').text(option.text).val(option.value));
}
});
if (selectSingleMatch === true && $(select).children().length === 1)
{
$(select).children().get(0).selected = true;
}
});
});
};
选项2
$(function () {
var fruitSelect = $("#FruitList"),
searchField = $("#SearchKey"),
options = FruitList.find("option").clone(); // clone into memory
// generic function to clean text
function sanitize(string)
{
return $.trim(string).replace(/\s+/g, ' ').toLowerCase();
}
// prepare the options by storing the
// "searchable" name as data on the element
options.each(function ()
{
var option = $(this);
option.data("sanitized", sanitize(option.text()));
});
// handle keyup
searchField.on("keyup", function (event)
{
var term = sanitize($(this).val()),matches;
// just show all options, if there's no search term
if (!term)
{
fruitSelect.empty().append(options.clone());
return;
}
// otherwise, show the options that match
matches = options.filter(function ()
{
return $(this).data("sanitized").indexOf(term) != -1;
}).clone();
fruitSelect.empty().append(matches);
});
});
function rearrangeList(list)
{
$(list).find("option").sort(byValue).appendTo(list);
}
但这似乎更多的代码行,有没有简单的方法来实现这个目的?
无需进行后端ajax调用。如何通过输入搜索字符串
来编写一个简单且较少的代码jquery来过滤此列表答案 0 :(得分:0)
让我们假设生成的html就像这样
<input type="text" id="filterText" />
<br/>
<select multiple>
<option>apples</option>
<option>apricots</option>
<option>blueberry</option>
<option>acai</option>
<option>bananas</option>
<option>cherry</option>
</select>
然后下面的js执行过滤器
$('#filterText').on('keyup', function() {
var filterWord = $(this).val().toLowerCase();
$('select').find('option').show()
$('select').find('option').not(':contains('+filterWord+')').hide()
});
在输入文本上按下某个键后,它会自动显示这些选项,然后隐藏那些不包含这些字符的选项