jquery
  1. jquery-filter

JQuery filter()

The jQuery filter() method is a powerful tool for selecting elements from a selected set based on specific criteria.

Syntax

The basic syntax for using the filter() method is as follows:

$(selector).filter(parameter)

Here, selector is the jQuery selector used for selecting a set of elements, and parameter is the specific criteria used for filtering the selected set.

Use

The filter() method is commonly used in situations where you need to narrow down a set of elements based on specific criteria. For example, you might use it to filter a list of items based on a user's search query or to select elements of a certain type or class.

Example

Here's an example of using the filter() method to select a set of table rows based on a certain condition:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

  <table>
    <tr><td>John</td><td>35</td></tr>
    <tr><td>Jane</td><td>25</td></tr>
    <tr><td>Bob</td><td>42</td></tr>
    <tr><td>Mike</td><td>29</td></tr>  
  </table>

  <input type="text" id="ageInput">
  <button>Filter by Age</button>

  <script>
    $(document).ready(function(){
      $("button").click(function(){
        // Remove background color property to reset
        $("tr").css("background-color", "");

        var age = parseInt($("#ageInput").val());
        $("tr").filter(function(){
          return $(this).find("td:eq(1)").text() > age;
        }).css("background-color", "#c8f7c5");
      });
    });
  </script>

</body>
</html>
Try Playground

In this example, we first define a table with 4 rows of data. We then create a button and an input field where the user can enter an age. When the button is clicked, we use the parseInt() function to convert the input value to an integer, and then use the filter() method to select only those rows where the age is greater than the input value. Finally, we set the background color of the selected rows to a light green color.

Summary

The filter() method in jQuery is a useful tool for selecting elements from a set based on specific criteria. Its simple and flexible syntax makes it an ideal choice for a variety of use cases, including filtering lists or tables, selecting elements based on user input, and more. Give it a try in your next jQuery project!

Published on: