How to dynamic filter options of <select > with jQuery?

前端 未结 12 620
轮回少年
轮回少年 2020-11-29 18:54



        
12条回答
  •  我在风中等你
    2020-11-29 19:21

    Slightly different to all the other but I think this is the most simple:

    $(document).ready(function(){
    
        var $this, i, filter,
            $input = $('#my_other_id'),
            $options = $('#my_id').find('option');
    
        $input.keyup(function(){
            filter = $(this).val();
            i = 1;
            $options.each(function(){
                $this = $(this);
                $this.removeAttr('selected');
                if ($this.text().indexOf(filter) != -1) {
                    $this.show();
                    if(i == 1){
                        $this.attr('selected', 'selected');
                    }
                    i++;
                } else {
                    $this.hide();
                }
            });
        });
    
    });
    

提交回复
热议问题