I have the following markup:
<input type="text" id="boBox" />
<ul id="boBoxData">
<li>1</li>
<li>12</li>
<li>123</li>
<li>1234</li>
<li>12345</li>
<li>123456</li>
<li>1234567</li>
<li>12345678</li>
</ul>
with the following JQuery code:
$(document).ready(function() {
$('#boBox').bind('keydown keypress keyup change', function () {
var search = $('#boBox').val();
if (search !== '') {
$('#boBoxData li').hide();
$('#boBoxData li[text*=' + search + ']').show();
} else {
$('#boBoxData li').show();
}
});
});
when I type text like '1' or '12' in the 'boBox' search field it is supposed to filter out all the LI's whose text doesn't contain my search data however for some reason it is displaying nothing instead. Why?
I have the following markup:
<input type="text" id="boBox" />
<ul id="boBoxData">
<li>1</li>
<li>12</li>
<li>123</li>
<li>1234</li>
<li>12345</li>
<li>123456</li>
<li>1234567</li>
<li>12345678</li>
</ul>
with the following JQuery code:
$(document).ready(function() {
$('#boBox').bind('keydown keypress keyup change', function () {
var search = $('#boBox').val();
if (search !== '') {
$('#boBoxData li').hide();
$('#boBoxData li[text*=' + search + ']').show();
} else {
$('#boBoxData li').show();
}
});
});
when I type text like '1' or '12' in the 'boBox' search field it is supposed to filter out all the LI's whose text doesn't contain my search data however for some reason it is displaying nothing instead. Why?
Share Improve this question asked May 21, 2012 at 13:16 William CallejaWilliam Calleja 4,17511 gold badges42 silver badges51 bronze badges4 Answers
Reset to default 7your example does not work because text is not an attribute of an li
.
Try using filter()
to search for the text instead:
$('#boBox').bind('keydown keypress keyup change', function() {
var search = this.value;
var $li = $("#boBoxData li").hide();
$li.filter(function() {
return $(this).text().indexOf(search) >= 0;
}).show();
});
Example fiddle
there is no text
property for li
. you can get the text()
property insted.
insted of:
$('#boBoxData li').hide();
$('#boBoxData li[text*=' + search + ']').show();
try
$('#boBoxData li').each(function(){
if ( ($this).text().indexOf(search) > -1 ) $(this).show();
else $(this).hide();
});
To find the element which contains the value from the checkbox, you have to loop through each element and use the .text() function to get the text-content of the tag:
$('#boBoxData li').each(function() {
if ($(this).text().indexOf(search) != -1) {
$(this).show();
}
});
$(document).ready(function () {
$("#boBoxData li").hide();
$('#boBoxData li').each(function (i) {
$(this).attr('data-text', function () {
return $(this).text();
});
});
$('#boBox').bind('change keypress keyup change', function () {
$("#boBoxData li").hide();
$('#boBoxData li[data-text*="' + $.trim($(this).val()) + '"]').show();
});
});
for live demo see this link: http://jsfiddle/nanoquantumtech/B7NxP/