简体   繁体   中英

Why do my all my <LI>'s remain selected when I clear/delete the value to search for in my input box

I need the help of the gurus and experts on this site.

The problem is that once I search for a value in my input box, everything works fine as expected, except for the fact that when the input box is cleared, all my <LI> 's remain "selected" thus leaving them highlighted. How can I get them to all go back to their default format of white / non-selected state?

I've put together a fiddle here for you here:

http://jsfiddle.net/uG9fq/2/

/* find item in list as you type */
    $("#refdocs").keyup(function(){ // onkeyup for the input field
        var pattern = new RegExp($(this).val()); // store current value of input field as a RegExp pattern (though it could just be a string)
        $("#refdocs_list li").each(function(){ // go through each item and try to match the pattern
            var text = $(this).text();
            if(text.match(pattern) !== null){
                $(this).addClass("selected"); // pattern found - set .selected
            }
            else{
                $(this).removeClass("selected"); // pattern not found - remove .selected
            }
        });
    });

It's because you're not checking for an empty value, which would match everything

$("#refdocs").keyup(function(){
    var val = $(this).val();
    var pattern = new RegExp(val);
    $("#refdocs_list li").each(function(){
        var text = $(this).text();
        if(text.match(pattern) !== null && val.length){
            $(this).addClass("selected");
        }
        else{
            $(this).removeClass("selected");
        }
    });
});

FIDDLE

A little easier on the eyes

$("#refdocs").on('keyup', function(){
    var val = this.value;
    $("#refdocs_list li").each(function() {
        $(this).toggleClass('selected', $(this).text().indexOf(val) != -1 && val.length > 0);
    });
});

you just need to remove selected class if the value was empty

if($(this).val() === ''){
    $('#refdocs_list ul li').removeClass('selected');
}

see my updated jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM