Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

92
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda