Question

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?

Était-ce utile?

La solution

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

Autres conseils

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();
});

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();
    }
});
 $(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/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top