2009-09-19 19 views

Trả lời

8

Tôi không chắc chắn lý do tại sao bạn có nhiều hơn một lựa chọn với giá trị như nhau, nhưng hoạt động này

$(document).ready(function() { 
 
    $('input').change(function() { 
 
    var filter = $(this).val(); 
 
    $('option').each(function() { 
 
     if ($(this).val() == filter) { 
 
     $(this).show(); 
 
     } else { 
 
     $(this).hide(); 
 
     } 
 
     $('select').val(filter); 
 
    }) 
 
    }) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select> 
 
    <option value="something1">something1</option> 
 
    <option value="something1">something1</option> 
 
    <option value="something2">something2</option> 
 
    <option value="something2">something2</option> 
 
    <option value="something2">something2</option> 
 
    <option value="something3">something3</option> 
 
    <option value="something3">something3</option> 
 
    <option value="something3">something3</option> 
 
</select> 
 
<input type="text" placeholder="something1">

+3

Tôi đã cố gắng để thực hiện điều này nhưng nó có thể không được trình duyệt chéo tương thích http://stackoverflow.com/questions/1271503/hide-options-in-a-select-list-using-jquery – James

69

HTML mẫu:

//jQuery extension method: 
 
jQuery.fn.filterByText = function(textbox) { 
 
    return this.each(function() { 
 
    var select = this; 
 
    var options = []; 
 
    $(select).find('option').each(function() { 
 
     options.push({ 
 
     value: $(this).val(), 
 
     text: $(this).text() 
 
     }); 
 
    }); 
 
    $(select).data('options', options); 
 

 
    $(textbox).bind('change keyup', function() { 
 
     var options = $(select).empty().data('options'); 
 
     var search = $.trim($(this).val()); 
 
     var regex = new RegExp(search, "gi"); 
 

 
     $.each(options, function(i) { 
 
     var option = options[i]; 
 
     if (option.text.match(regex) !== null) { 
 
      $(select).append(
 
      $('<option>').text(option.text).val(option.value) 
 
     ); 
 
     } 
 
     }); 
 
    }); 
 
    }); 
 
}; 
 

 
// You could use it like this: 
 

 
$(function() { 
 
    $('select').filterByText($('input')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select> 
 
    <option value="hello">hello</option> 
 
    <option value="world">world</option> 
 
    <option value="lorem">lorem</option> 
 
    <option value="ipsum">ipsum</option> 
 
    <option value="lorem ipsum">lorem ipsum</option> 
 
</select> 
 
<input type="text">

Live demo tại đây: http://www.lessanvaezi.com/filter-select-list-options/

+0

Cảm ơn bạn rất nhiều cho đoạn mã. Điều này đã giúp tôi tiết kiệm rất nhiều thời gian chỉ trong một dự án nhỏ - hoạt động như một sự quyến rũ! –

+0

Thật tuyệt, nhưng trong trường hợp của tôi, hộp văn bản lọc có thể chứa một số văn bản ngay sau khi tải trang. Làm thế nào tôi có thể bắt đầu lọc ngay sau khi tải trang? –

+0

Tìm thấy nó! '$ ('input'). change();' –

3

Đây là giải pháp đơn giản, nơi bạn sao chép các tùy chọn danh sách và giữ chúng trong đối tượng để khôi phục sau này. Các kịch bản dọn dẹp danh sách và chỉ thêm các tùy chọn có chứa văn bản đầu vào. Điều này cũng nên làm việc qua trình duyệt. Tôi có một số sự giúp đỡ từ bài đăng này: https://stackoverflow.com/a/5748709/542141

Html

<input id="search_input" placeholder="Type to filter"> 
<select id="theList" class="List" multiple="multiple"> 

hay dao cạo

@Html.ListBoxFor(g => g.SelectedItem, Model.items, new { @class = "List", @id = "theList" }) 

kịch bản

<script type="text/javascript"> 
    $(document).ready(function() { 
    //copy options 
    var options = $('#theList option').clone(); 
    //react on keyup in textbox 
    $('#search_input').keyup(function() { 
     var val = $(this).val(); 
     $('#theList').empty(); 
     //take only the options containing your filter text or all if empty 
     options.filter(function (idx, el) { 
     return val === '' || $(el).text().indexOf(val) >= 0; 
     }).appendTo('#theList');//add it to list 
    }); 
    }); 
</script> 
0

Cập nhật câu trả lời của Lessan cũng để giữ các thuộc tính của các tùy chọn.

Đây là lần đầu tiên tôi trả lời trên Stack Overflow vì vậy không chắc tôi có nên chỉnh sửa câu trả lời hay tự tạo câu trả lời hay không.

jQuery.fn.allAttr = function() { 
    var a, aLength, attributes, map; 
    if (!this[0]) return null; 
    if (arguments.length === 0) { 
    map = {}; 
    attributes = this[0].attributes; 
    aLength = attributes.length; 
    for (a = 0; a < aLength; a++) { 
     map[attributes[a].name.toLowerCase()] = attributes[a].value; 
    } 
    return map; 
    } else { 
    for (var propin arguments[0]) { 
     $(this[0]).attr(prop, arguments[0][prop]); 
    } 
    return this[0]; 
    } 
}; 


jQuery.fn.filterByText = function(textbox) { 
    return this.each(function() { 
    var select = this; 
    var options = []; 
    $(select).find('option').each(function() { 
     options.push({ value: $(this).val(), 
     text: $(this).text(), 
     allAttr: $(this).allAttr() }); 
    }); 
    $(select).data('options', options); 

    $(textbox).bind('change keyup', function() { 
     var search = $.trim($(this).val()); 
     var regex = new RegExp(search, "gi"); 

     $.each($(select).empty().data('options'), function(i, option) { 
     if (option.text.match(regex) !== null) { 
      $(select).append(
      $('<option>').text(option.text) 
      .val(option.value) 
      .allAttr(option.allAttr) 
     ); 
     } 
     }); 
    }); 
    }); 
}; 
+0

nó sẽ dễ dàng hơn nhiều để ẩn những tùy chọn bạn không muốn. – Dementic

5

Hơi khác nhau cho tất cả các khác nhưng tôi nghĩ rằng đây là đơn giản nhất:

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

}); 
+0

Sự kết hợp giữa Mottie và Hersker –

0

Bạn có thể sử dụng Select2 plugin cho việc tạo ra một bộ lọc như vậy. Với công việc mã hóa của lô này có thể tránh được. Bạn có thể lấy plugin từ https://select2.github.io/

Plugin này rất đơn giản để áp dụng và ngay cả công việc nâng cao cũng có thể dễ dàng thực hiện với nó. :)

0

Tôi đã có một vấn đề tương tự với điều này, vì vậy tôi đã thay đổi câu trả lời được chấp nhận để tạo ra một phiên bản chung hơn của hàm. Tôi nghĩ tôi sẽ để nó ở đây.

var filterSelectOptions = function($select, callback) { 

    var options = null, 
     dataOptions = $select.data('options'); 

    if (typeof dataOptions === 'undefined') { 
     options = []; 
     $select.children('option').each(function() { 
      var $this = $(this); 
      options.push({value: $this.val(), text: $this.text()}); 
     }); 
     $select.data('options', options); 
    } else { 
     options = dataOptions; 
    } 

    $select.empty(); 

    $.each(options, function(i) { 
     var option = options[i]; 
     if(callback(option)) { 
      $select.append(
       $('<option/>').text(option.text).val(option.value) 
      ); 
     } 
    }); 
}; 
0
<script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
<script language='javascript'> 
jQuery.fn.filterByText = function(textbox, selectSingleMatch) { 
    return this.each(function() { 
    var select = this;`enter code here` 
    var options = []; 
    $(select).find('option').each(function() { 
     options.push({value: $(this).val(), text: $(this).text()}); 
    }); 
    $(select).data('options', options); 
    $(textbox).bind('change keyup', function() { 
     var options = $(select).empty().scrollTop(0).data('options'); 
     var search = $.trim($(this).val()); 
     var regex = new RegExp(search,'gi'); 

     $.each(options, function(i) { 
     var option = options[i]; 
     if(option.text.match(regex) !== null) { 
      $(select).append(
      $('<option>').text(option.text).val(option.value) 
     ); 
     } 
     }); 
     if (selectSingleMatch === true && 
      $(select).children().length === 1) { 
     $(select).children().get(0).selected = true; 
     } 
    }); 
    }); 
}; 

    $(function() { 
    $('#selectorHtmlElement').filterByText($('#textboxFiltr2'), true); 
    }); 
</script> 
1

đơn giản hơn nhiều mã sau đó hầu hết các giải pháp khác. Tìm văn bản (phân biệt chữ hoa chữ thường) và sử dụng CSS để ẩn/hiển thị nội dung. Tốt hơn nhiều so với lưu trữ một bản sao của dữ liệu.

Chuyển sang phương thức này là id của hộp chọn và id của đầu vào chứa bộ lọc.

function FilterSelectList(selectListId, filterId) 
{ 
    var filter = $("#" + filterId).val(); 
    filter = filter.toUpperCase(); 

    var options = $("#" + selectListId + " option"); 
    for (var i = 0; i < options.length; i++) 
    { 
     if (options[i].text.toUpperCase().indexOf(filter) < 0) 
      $(options[i]).css("display", "none"); 
     else 
      $(options[i]).css("display", "block"); 
    } 
}; 
Các vấn đề liên quan