0

I would like to toggle certain rows containing certain data but I just cant seen to get it working,I have tried many variations. Somewhere i am missing something small. My latest variation looks like this.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script>
  $(document).ready(function() {
    $("tr:contains(dog)").hide().css({
      "background-color": "orange",
      "color": "black",
      "border": "1px solid black"
    });
  });

  $('#showdog').click(function() {
    $("tr:contains(dog)").toggle();
  });
</script>

<button id="showdog">show rec</button>

<table>
  <tr><td>dog</td></tr>
  <tr><td>cat</td></tr>
  <tr><td>mouse</td></tr>
  <tr><td>dog</td></tr>
  <tr><td>dog</td></tr>
  <tr><td>cat</td></tr>
  <tr><td>dog</td></tr>
  <tr><td>rabbit</td></tr>
</table>

I want to be able to toggle certain rows in an html table that contain certain data, typically the hide show method, i have only been successful in hiding or showing all the tr's. What am i missing ?.

1
  • Move the $('#showdog').click(function() { $("tr:contains(dog)").toggle(); }); to inside the document.ready function so the button is available to the script Commented Jun 8 at 9:02

1 Answer 1

-1

You are trying to attach an event handler to the #showdog button, before it's rendered to the DOM. Move the $('#showdog').click(function() { inside the .ready() block, or move the entire script to the end of the body element.

Note: you can shorten $(document).ready(function() { to $(function() {.

$(document).ready(function() {
  $("tr:contains(dog)").hide().css({
    "background-color": "orange",
    "color": "black",
    "border": "1px solid black"
  });

  $('#showdog').click(function() {
    $("tr:contains(dog)").toggle();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<button id="showdog">show rec</button>

<table>
  <tr><td>dog</td></tr>
  <tr><td>cat</td></tr>
  <tr><td>mouse</td></tr>
  <tr><td>dog</td></tr>
  <tr><td>dog</td></tr>
  <tr><td>cat</td></tr>
  <tr><td>dog</td></tr>
  <tr><td>rabbit</td></tr>
</table>

->

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Ori, took me a while to figure out what you were telling me, then finally i realized my mistake. Again many thanks.
@totitechcare - you're welcome :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.