William Calleja
William Calleja

Reputation: 4175

Building a quick search box with JQuery

I have the following markup:

<input type="text" id="comboBox" />
<ul id="comboBoxData">
    <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() {   
    $('#comboBox').bind('keydown keypress keyup change', function () {
        var search = $('#comboBox').val();
        if (search !== '') {
            $('#comboBoxData li').hide();
            $('#comboBoxData li[text*=' + search + ']').show();
        } else {
            $('#comboBoxData li').show();
        }
    });
});

when I type text like '1' or '12' in the 'comboBox' 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?

Upvotes: 3

Views: 7009

Answers (4)

Thulasiram
Thulasiram

Reputation: 8552

 $(document).ready(function () {
        $("#comboBoxData li").hide();

        $('#comboBoxData li').each(function (i) {
            $(this).attr('data-text', function () {
                return $(this).text();
            });
        });

        $('#comboBox').bind('change keypress  keyup change', function () {
            $("#comboBoxData li").hide();
            $('#comboBoxData li[data-text*="' + $.trim($(this).val()) + '"]').show();
        });
    });​

for live demo see this link: http://jsfiddle.net/nanoquantumtech/B7NxP/

Upvotes: 0

Stefan Fandler
Stefan Fandler

Reputation: 1141

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:

$('#comboBoxData li').each(function() {
    if ($(this).text().indexOf(search) != -1) {
        $(this).show();
    }
});

Upvotes: 0

Sagiv Ofek
Sagiv Ofek

Reputation: 25270

there is no text property for li. you can get the text() property insted.
insted of:

$('#comboBoxData li').hide();
$('#comboBoxData li[text*=' + search + ']').show();

try

$('#comboBoxData li').each(function(){
   if ( ($this).text().indexOf(search) > -1 ) $(this).show(); 
   else $(this).hide();
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337620

your example does not work because text is not an attribute of an li.

Try using filter() to search for the text instead:

$('#comboBox').bind('keydown keypress keyup change', function() {
    var search = this.value;
    var $li = $("#comboBoxData li").hide();
    $li.filter(function() {
        return $(this).text().indexOf(search) >= 0;
    }).show();
});

Example fiddle

Upvotes: 7

Related Questions