user2005657
user2005657

Reputation: 627

jquery how to show a table row based on an html5 attribute of a checked checkbox

Hi say I have the following html:

<input type-checkbox [email protected][i].Id />

<table>
  @for(var i=0; i < @Model.TestDtos[i].Count; i++)
  {
    <tr class="hidden" [email protected][i].Id>Show some stuff</tr>
  }
</table>

So I'm wanting to make it that when the checkbox with matching data-testid value is checked the table row becomes visible.

I tried:

    if ($(this).is(":checked")) {

        var testid = $(this).data('testid');
        $("tr[data-testid=testid").show();
    }

The problem is the IDE is saying that testid is never used. I'm unsure how to get the value from the checkbox data-testid and use it to find the correct row to show.

Upvotes: 0

Views: 266

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388406

testid is a variable, so you need to use string concatenation here

$('tr[data-testid="' + testid + '"]').show()

Demo: Fiddle

But what you really need might be

$(':checkbox').click(function(){
    var fn = this.checked ? 'show' : 'hide';
    var testid = $(this).data('testid');
    $('tr[data-testid="' + testid + '"]')[fn]();
})

Demo: Fiddle

Upvotes: 3

George
George

Reputation: 36794

You need to use string concatenation to use your variable. You are also missing a square bracket from the end of the selector. Try this:

$("tr[data-id='"+testid+"']").show();

Upvotes: 1

Related Questions