t0m
t0m

Reputation: 17

JQuery hide all elements

I want to hide the table row if one of the <span> tags has the class from the value variable.

The variable val comes from a select box.

$(".hostgroup").change(function(event) {
  var val = $(this).val();
  console.log(val);
  $("#groups > span").each(function() {
    $(this).closest("tr").show();
    $(this).removeClass("hd");
  });
  $("#groups > span").each(function() {
    if ($(this).hasClass(val)) {} else {
      $(this).closest("tr").hide();
      $(this).closest("tr").addClass("hd");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="hostgroup" data-placeholder="Choose a hostgroup...">
    <option value="delete">delete</option>
    <option value="add">add</option>
    <option value="OS">OS</option>>    
</select>

<tr>
  <td id="groups">
    <span class="add">add,</span>
    <span class="OS">OS,</span>
  </td>
</tr>

<tr>
  <td id="groups">
    <span class="delete">delete,</span>
    <span class="OS">OS,</span>
  </td>
</tr>

For example: I select delete and it should only display table rows that not have got a <span> with the delete class. But now it will hide all results.

Upvotes: 0

Views: 90

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could search for the class based on the tr, see the working example below :

$(".hostgroup").change(function(event) {
  var val = $(this).val();

  $("tr").each(function() {
    if ( $(this).find('.' + val).length ) {
      $(this).closest("tr").addClass("hd");
    } else {
      $(this).closest("tr").removeClass("hd");
    }
  });
});
.hd {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="hostgroup">
  <option></option>
  <option>add</option>
  <option>OS</option>
  <option>delete</option>
</select>
<table>
  <tr>
    <td class="groups">
      <span class="add">add,</span>
      <span class="OS">OS,</span>
    </td>
  </tr>

  <tr>
    <td class="groups">
      <span class="delete">delete,</span>
      <span class="OS">OS,</span>
    </td>
  </tr>
</table>

Upvotes: 0

Tomasz Cekało
Tomasz Cekało

Reputation: 41

$("span.delete").parent().parent().hide()

will hide entire rows with spans in them with "delete" class. Swap the class to the value of your choosing in the "change" event.

Edit:

It should be like this:

$(".hostgroup").change(function(event) {
var val = $(this).val();
console.log(val);
$("span."+val).parent().parent().hide()
});

Upvotes: 1

Related Questions