Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have two separate lists both sitting side by side. How can I refactor the code below to only have one filter function for both lists?

$("input.filterInput").keyup(function() {
    filter(this); 
});

function filter(element) {
    var value = $(element).val();
    $(".pdfList > li").each(function (){
        if ($(this).text().indexOf(value) > -1) {
                $(this).show();
        } else {
            $(this).hide();
        }
    });
}

$("input.filterInput2").keyup(function() {
    filter2(this); 
});

function filter2(element) {
    var value = $(element).val();
    $(".pdfList2 > li").each(function (){
        if ($(this).text().indexOf(value) > -1) {
                $(this).show();
        } else {
            $(this).hide();
        }
    });
}
share|improve this question

1 Answer 1

up vote 1 down vote accepted

You'll have the following two inputs in your HTML.

<input id="filterInput1" />
<input id="filterInput2" />

Then you can wire them both up together, or split it into separate assignments:

$('#filterInput1, #filterInput2').each(function () {
    $(this).keyup(function () {
        filter(this);
    });
});

Finally, check the ID of the element that triggered the function call to see what list you should be trying to highlight:

function filter(element) {
    var value = $(element).val(),
        selector;

    if (element.id === 'filterInput1') {
        selector = '.pdfList';
    } else if (element.id === 'filterInput2') {
        selector = '.pdfList2';
    } else {
        return; // Or throw an error, whatever you feel is more appropriate.
    }

    // Now the dropdown selector is stored in the variable, and will change which
    // it is looking at depending on who called it.
    $(selector + " > li").each(function (){
        if ($(this).text().indexOf(value) > -1) {
                $(this).show();
        } else {
            $(this).hide();
        }
    });
}
share|improve this answer
    
I tried that. It filters both independent lists at the same time... –  JoelL Feb 23 at 17:46
    
Yeah, I just went back and took another look and realized. Give me a minute. –  krillgar Feb 23 at 17:47
    
Haha ok thanks! –  JoelL Feb 23 at 17:47
1  
im just using them to distinguish between input fields. I should probably make them ids –  JoelL Feb 23 at 17:59
1  
Got it. Thank you –  JoelL Feb 23 at 18:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.