How to filter select list options

Here’s a jQuery extension method to filter the elements of a select list (option tags). It binds to a textbox, and as you type in the textbox the select list gets filtered to match what you are typing.

jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
  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)
          );
        }
      });
      if (selectSingleMatch === true &&
          $(select).children().length === 1) {
        $(select).children().get(0).selected = true;
      }
    });
  });
};

Parameters:

  • textbox
    This could be a jQuery selector, a jQuery object, or a DOM object.
  • selectSingleMatch
    This is optional, if you set it to true, when the filtered list includes only one item, that item will be automatically selected.

For example:

$(function() {
  $('#select').filterByText($('#textbox'), true);
});

Live example (or in a new window):

You can play around with it on jsbin: http://jsbin.com/egogeh/edit

What it does:

When you invoke the function on a select object, it finds all child option tags and saves their text and values into an array. This array is saved to the select object itself as a HTML5 custom data attribute, called data-options. Then, when a change or keyup event fires on the associated textbox, the select list is emptied, and for any entries in the array that match the search text a new option element is created.

This entry was posted in Technology and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Raam
    Posted 2011/08/25 at 2:14 pm | Permalink

    Hi, Thats a good one…. Thank you.. I have a question if you could help me with it will be great..

    I am creating a small troubleshooting guide which is created in Jquery and HTML. When user selects a step this is designed to give next step to try and from there next one in a flow chart style.

    I want to add a textbox to which the selections will auto populate. After troubleshooting they should be able to copy all selected items from the text box. Can anyone help me with a code which will auto populate all user selected items from the flow into a text box.

    Please find the code I used for the troubleshooting guide. Any help will highly appreciated.. Thanks in advance..

    $(‘document’).ready(function(){
    var count = 0;
    $(‘#questions’).hide();
    $(‘#answers’).hide();
    $(‘#questions tr:nth-child(2)’).attr(‘id’,'currow’);
    var q1 = $(‘#currow td:nth-child(2)’).html();
    var q3 = ” + q1 + ” ;
    var a1 = $(‘#currow td:nth-child(3)’).html();
    var r1 = q3 + a1 +”;
    $(‘#showquestion’).html(r1);

    $(‘li’).live(‘click’,function(){
    $(this).addClass(‘selected’).siblings().removeClass(‘selected’);
    var target = $(this).attr(‘id’);
    var parid = $(this).parent().parent().attr(‘id’);
    var parnum = parseInt(parid.slice(1,3));
    count = count + 1;
    var ps = $(‘#showquestion div’).length;
    $(‘#showquestion div’).each(function() {
    var divid = $(this).attr(‘id’);
    var divnum = parseInt(divid.slice(1,3));
    if(divnum > parnum)
    $(this).remove()
    })
    $(‘td’ ).each(function(){
    var qnum = $(this).text();
    if(qnum == target) {
    var q = $(this).next(‘td’).html();
    var q2 = ” + q + ”;
    var a = $(this).next(‘td’).next(‘td’).html();
    var qs = $(‘#showquestion’).html();
    var r = qs + q2 + a +”;
    $(‘#showquestion’).html(r);
    window.scrollBy(0,400);
    }
    })
    })
    })

    Support System

    No
    Question/Heading
    Answers

    1
    Question 1

    Option 1
    Option 2
    Option 3

    2
    Level 2 – from question 1 Option 1

    Option 1
    Option 2

    3
    Level 2 – from question 1 – no

    Option 1
    Option 2
    Option 3
    Option 4

    4
    Level 3 – from level 2 option 1

    Option 1
    Option 2
    Option 3
    Option 4

    Text Field:

  2. PR
    Posted 2011/11/09 at 4:28 pm | Permalink

    This is awesome! Just the solution I had been looking for. Came across other filter functions but it wouldn’t work on my Struts2 select list. Thank you for posting an optimal solution.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting