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 want to filter the otions of a large select group based on text input in a textbox. Currently I am using the below jquery to filter from a SELECT group based on the text of a input box. Can you please tell me whether there is any more efficient way to do this? My Select group is very large with around 7000 entry, that's why I am looking for the most optimized way.

var fullcelllist = $();
var lastVal ="";

    $("#celllist option").each(function(){

$("#filtercell").keyup(function() {
    if(lastVal.length < $(this).val().length){
        $("#celllist option:not([value*='"+$(this).val().toUpperCase()+"'])").each(function() {
        stregexp = new RegExp($(this).val(),"i");
        temparr = $.grep(fullcelllist, function (value) {
        if(value.match(stregexp)) return value;
            return null;
        newopt = "";
            newopt += "<option value='"+temparr[i]+"'>"+temparr[i]+"</option>"; 
    lastVal = $(this).val();

<input type="text" id="filtercell">
<select id ="celllist" multiple="multiple">
// HERE all OPTIONS using PHP
share|improve this question

2 Answers 2

up vote 0 down vote accepted

Your jQuery could be somewhat more efficient, if you save reused $(...) chunks in their own variables. Also, I think you will see some benefit to replacing some jQuery constructs with their pure JS alternatives ($.each -> for, etc..)

var fullcelllist = $(),
    lastVal ="",
    $celllistOption = $("#celllist option");

// ...

$("#filtercell").keyup(function() {
    var $this = $(this),
        $thisVal = $this.val();

// ...
share|improve this answer
thanks .. i didn't know that reusing $(...) would hamper my performance! Good to know, I'll change accordingly. –  Abdullah Fahim Jan 12 '13 at 8:29

You can do something like this

var options = $("#celllist option"); // cache all your options right away

$("#filtercell").keyup(function () {
  var stregexp = new RegExp($(this).val(), "i"); // your regex
  $("#celllist").append(options); // append will add all missing options
  var x = $.grep(options, function (value) { // get all the options where value doesn't match
    return !value.value.match(stregexp)
  $(x).detach(); // detach them from dom


share|improve this answer
wow .. I'll give that a try ... thanks –  Abdullah Fahim Jan 12 '13 at 8:30

Your Answer


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.