Home > OS >  Using a HTML-id created by forloop.counter in javascript
Using a HTML-id created by forloop.counter in javascript

Time:11-27

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>

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related