abdfahim
abdfahim

Reputation: 2553

jquery filtering checkbox list by input box

I have a long checkbox list (with same name). I want create a filtering system based on input in a text box. I mean, when I write "ter" in my text box, I want to show only those chechboxes which values matches %ter% (means have the phrase "ter" anywhere). What is the best way to achieve that using jquery? My apologies as I am very new to jquery.

<input type="checkbox" name="chk" id="chk1" value="casual">casual
<input type="checkbox" name="chk" id="chk2" value="intermediate">intermediate
<input type="checkbox" name="chk" id="chk3" value="hunter">hunter
<input type="checkbox" name="chk" id="chk4" value="forest">forest
<input type="checkbox" name="chk" id="chk5" value="term">extreme
<input type="checkbox" name="chk" id="chk6" value="river">river
<input type="checkbox" name="chk" id="chk7" value="beach">beach
<input type="text" id="chkfilter">

So, whenever I write "ter" in the text box, checkbox 2,3 and 5 should be visible, others should be hidden/gone. How to do that? Using div for each individual item? Also, how to search using jquery to match %ter%

Upvotes: 7

Views: 9303

Answers (3)

nikunj sobhashana
nikunj sobhashana

Reputation: 181

$(":checkbox").each(function () {
    $(this).add(this.nextSibling)
        .add(this.nextSibling.nextSibling)
        .wrapAll("<label class='country'></label>")
})
$("#text").keyup(function () {
    var re = new RegExp($(this).val(), "i")
    $('.country').each(function () {
        var text = $(this).text(),
            matches = !! text.match(re);
        $(this).toggle(matches)
    })
})

i m using this solution for filter checkbox name using textbox value

Upvotes: 2

adeneo
adeneo

Reputation: 318212

When you type something in the textbox, check the checkboxes to see it that string exists in the value with indexOf, and set the display property based on that (I used block, but inline is probably correct for checkboxes):

$('#chkfilter').on('keyup', function() {
    var query = this.value;

    $('[id^="chk"]').each(function(i, elem) {
          if (elem.value.indexOf(query) != -1) {
              elem.style.display = 'block';
          }else{
              elem.style.display = 'none';
          }
    });
});

The text after the checkbox is not part of the checkbox and will not be hidden, to do that you should probably wrap it in a label and do something like this JSBIN ??

Upvotes: 13

Nic
Nic

Reputation: 581

You could filter by value using the jQuery "Attribute Contains Selector" and then hide or disable the checkboxes. About the label - there are many ways to do this. Either wrap the whole thing into a div and use .parent() on the filtered checkboxes to hide the whole thing, or wrap the label text into a <label> with a corresponding id to hide it afterwards.

Take a look at the jQuery API Docs: jQUery API - Attribute Contains Selector

Upvotes: 2

Related Questions