Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda