Henrik Petterson
Henrik Petterson

Reputation: 7104

Target two fields when searching

I have this layout:

<input id="search">

<div class="entry">
  <div class="title">hello</div>
  <div class="description">lorem</div>
</div>

<div class="entry">
  <div class="title">ipsum</div>
  <div class="description">test</div>
</div>

And I allow users to search the entry divs by the content of the title div:

jQuery(document).ready(function() {

    jQuery("#search").on("keyup click input", function () {
        var val = jQuery(this).val();
        if (val.length) {
            jQuery(".entry").hide().filter(function () {
                return jQuery('.title',this).text().toLowerCase().indexOf(val.toLowerCase()) != -1;
            }).show();
        }
        else {
            jQuery(".entry").show();
        }
    });

});

Works great. Try jsFiddle.

My question is, how do I make it so the search targets both the content of the title div and the description field?

Upvotes: 1

Views: 61

Answers (2)

Milan Chheda
Milan Chheda

Reputation: 8249

In the filter function, you can add an OR condition that can check the description and filter results on title or description.

jQuery(document).ready(function() {

  jQuery("#search").on("keyup click input", function() {
    var val = jQuery(this).val();
    if (val.length) {
      jQuery(".entry").hide().filter(function() {
        return jQuery('.title, .description', this).text().toLowerCase().indexOf(val.toLowerCase()) != -1;
      }).show();
    } else {
      jQuery(".entry").show();
    }
  });

});
.entry {
  background: #fff;
  margin-bottom: 10px;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search">

<div class="entry">
  <div class="title">hello</div>
  <div class="description">lorem</div>
</div>

<div class="entry">
  <div class="title">ipsum</div>
  <div class="description">test</div>
</div>

Upvotes: 3

If you want it to search for both title and description use this.

return jQuery('.title, .description',this)

Then it will look like

jQuery(".entry").hide().filter(function () {
    return jQuery('.title, .description',this).text().toLowerCase().indexOf(val.toLowerCase()) != -1;
}).show();

Here is a link so you can test it.

Upvotes: 6

Related Questions