Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
Using a HTML-id created by forloop.counter in javascript

I have a table where each row contains a product and a checkbox. I now want to change the text-decoration depending on the checkbox. My javascript code worked but only at the first row. I realized that the id I was using was not unique. Therefore, I have added a forloop.counter to create unique ids. But now I did not find a solution for my javascript to handle these ids. The table has always a different amount of rows. Does anyone have an idea?

Many thanks in advance!

My HTML code

{% for item in items %}
<tr>
<td name="product" id="product{{ forloop.counter }}">{{ item.product }}</td>
<td><input type="checkbox" id="checkbox{{ forloop.counter }}"></td>
</tr>
{% endfor %}

My javascript which is included in the html.

<script>
    document.getElementById('checkbox').onclick = function() {
        document.getElementById('product').style.textDecoration = this.checked ? "line-through" : "none";
    };
</script>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You don't need ids to associate the checkbox and product, you can simply use classes and find the .product with the same parent as the clicked checkbox.

Here's a quick example using event delegation applied to the table watching for clicks on checkboxes. It uses closest() to access the clicked checkboxes tr ancestor which is then queried for a child element with class product.

document.getElementById('table1').addEventListener('click', function(event) {
  if (event.target.type === 'checkbox') {
    const product = event.target.closest('tr').querySelector('.product');
    product.style.textDecoration = event.target.checked ? "line-through" : "none";
  }
});
<table id="table1">
  <tr>
    <td name="product" class="product">product 1</td>
    <td><input type="checkbox" ></td>
  </tr>
  <tr>
    <td name="product" class="product">product 2</td>
    <td><input type="checkbox" ></td>
  </tr>
  <tr>
    <td name="product" class="product">product 3</td>
    <td><input type="checkbox" ></td>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!