How to filter an html ajax response's elements before inserting into document?

Viewed 434

I am working with a server that responds with an HTML response of the form:

<div>
<table>
  <thead>
    <tr>
    <th>Name</th>
    <th>Country</th>
  </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Doe</td>
      <td>USA</td>
    </tr>
    <tr>
      <td>James Doe</td>
      <td>Canada</td>
    </tr>
     <tr>
      <td>Jonas Doe</td>
      <td>UK</td>
    </tr>
  </tbody>
</table>
</div>

My problem is that, before I insert this table, I want to filter the rows. For example, let's say I wanted to only have the rows with USA as the value in the second cell.

How could I do this?

Here's my current status in trying to solve this problem.

https://jsfiddle.net/bmp6a4gh/

In essence, Im trying to create a function that accepts the html string and injects a string (of the same format) but with the filtered rows.

function processResponse(html){
  var $html = $(html);
  //perform filtering here
  //I only want elements from USA
  $html.filter(function(index, element){
    return true;
  });
  $("#response").html($html);
}
1 Answers

You can first hide all trs which is inside tbody and then use filter to show only those row which have data i.e : USA.

Demo Code :

var simulatedResponse =
  "<div><table><thead><tr><th>Name</th><th>Country</th></tr></thead><tbody> <tr><td>John Doe</td><td>USA</td> </tr><tr><td>James Doe</td><td>Canada</td></tr><tr><td>Jonas Doe</td><td>UK</td></tr><tr><td>Jonas Doe</td><td>UK</td> </tr> </tbody></table></div>"

function processResponse(html) {
  var $html = $(html);
  //hide all trs inside tbody
  $html.find("tbody  tr ").hide();
  //filter trs
  $html.find("tbody  > tr  td").filter(function() {
  //check if value in td is Usa
    return $(this).text().indexOf("USA") == 0;
  }).parent().show();//show that tr
  $("#response").html($html);
}

// handle click and add class
var button = $("button");
button.on("click", () => {
  $("#response").html("");

  /* $.ajax({
       method: "post",
       url: "/echo/html/",
       data: simulatedResponse
     })
     .done(processResponse);*/
     //call function
  processResponse(simulatedResponse);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Perform Search</button>
<div id="response"></div>

Related