Sort a table by drop down values (simplify my code)

前端 未结 4 1983
小蘑菇
小蘑菇 2021-01-23 17:37

I have a table. I want the user to be able to be able to filter the table by the option they pick in a given drop down. I have it working, but it\'s messy and hard to add new ro

4条回答
  •  没有蜡笔的小新
    2021-01-23 18:11

    You can change your html markup like this

    cats
    cats
    dogs
    birds
    dogs

    Then your jQuery

    $('#selectFilter').change(function(){
        var trs = $('#animal tr'); 
        if(this.value == ''){  // if first option picked show all
             trs.show(); 
        }else{
           var $el = $('.'+this.value);  // element to show
           trs.not($el).hide(); // hide all but the elements to show
           $el.show();       // show elements
        }
    });
    

    FIDDLE

提交回复
热议问题