Heisenberg
Heisenberg

Reputation: 5299

How to increment data index in javascript

I tried to update data attribute as my work below.

When I click square,data attribute should be incremented.

But the result is a little bit different. It seems not to be incremented.

How can I fix them?

And Why this issue inccured?

Thanks

$("td").click(function() {
  index=$(this).data('layer');
  index+=1
  $(this).attr('data-layer',index);
  console.log(this);
});
td {
border:solid black 1px;
width:50px;
height:50px;
cursor:pointer;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td data-layer="0"></td>
  </tr>
</table>

Upvotes: 3

Views: 854

Answers (2)

gaetanoM
gaetanoM

Reputation: 42054

An Html element can have a dataset and/or an attribute.

In your code you get the value of the dataset and change like if it is an attribute. This is your mistake.

For more details see .data() and .attr().

If you are inrested in attribues you need to use:

$("td").click(function() {
    index=$(this).attr('data-layer');
    index = index + 1;
    $(this).attr('data-layer',index);
    console.log(this);
});

Instead, if you need to use dataset:

$("td").click(function() {
    index=$(this).data('layer');
    index = index + 1;
    $(this).data('layer',index);
    console.log($(this).data('layer'));
});
td {
      border:solid black 1px;
      width:50px;
      height:50px;
      cursor:pointer;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <tr>
        <td data-layer="0"></td>
    </tr>
</table>

Upvotes: 3

Nicolae Maties
Nicolae Maties

Reputation: 2665

$("td").click(function() {
  const index = $(this).attr('data-layer');
  const newIndex = Number(index) + 1;
  $(this).attr('data-layer', newIndex);
  console.log(this);
});
td {
border:solid black 1px;
width:50px;
height:50px;
cursor:pointer;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td data-layer="0"></td>
  </tr>
</table>

Upvotes: 1

Related Questions