I'm new to playwright and not sure how to approach this issue. I have a table with data, and the first column of each row has a checkbox. I want to be able to select the correct row to click the checkbox. What I'm not sure about is how to get the row.
My table:
| | ID | Name | Phone
| [] | 3745 | Frank Smith | 485-555-9394
| [] | 9394 | Joe Johnson | 384-555-2332
In HTML:
<table>
<thead>
<tr>
<th></th>
<th>ID</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr role="row" class="odd">
<td><input type="checkbox" name="personid"></td>
<td>3745</td>
<td>Frank Smith</td>
<td>485-555-9394</td>
</tr>
<tr role="row" class="even">
<td><input type="checkbox" name="personid"></td>
<td>9394</td>
<td>Joe Johnson</td>
<td>384-555-2332</td>
</tr>
</tbody>
</table>
Now, I want to select the checkbox associated with user ID 9394.
My original solution is (in nodejs):
page.locator('table tbody tr': {hasText: '9394'}.locator('td').nth(0).locator('input').check();
However, as you can see in the above example, it will select the row with the phone number that ends in 9394 or it will give me an error because it returned multiple rows.
My other thought is to do something like:
page.locator('table tbody tr td:nth(1)', {hasText: '9394'}). ???
I'm just not sure how to get back to the previous td input
in the row to click the checkbox.
Instead of using hasText
, you can also define a sub-locator that the elements have to contain and reference it using has
.
Assuming the id is always in the second column, you can use the following code:
const idLocator = page.locator('td:nth-child(2)', { hasText: '9394' });
const checkbox = page.locator('table tbody tr', { has: idLocator }).locator('input[type=checkbox]');
await checkbox.check();