Search code examples
javascripthtmlgetelementbyid

How to change value of one table data tag with one button press


This is my JS code, what I'm trying to do is click the button with the id="tg-13", just display a 13 in the td. But what really happens when I click the "tg-13" button, all the numbers appear. How can I solve this?

 <tr onclick="aparecer()">
    <td class="tg-kpoh" style="text-align: center;">J</td>
    <td id="tg-13" style="text-align: center;"><button>?</button></td>
    <td id="tg-10" style="text-align: center;"><button>?</button></td>
    <td id="tg-45" style="text-align: center;"><button>?</button></td>
    <td id="tg-47" style="text-align: center;"><button>?</button></td>
    <td id="tg-35" style="text-align: center;"><button>?</button></td>
  </tr>

Function - aparaecer()

function aparecer() {

    document.getElementById("tg-13").innerHTML = "13";

    document.getElementById("tg-10").innerHTML = "10";

    document.getElementById("tg-45").innerHTML = "45";  

    document.getElementById("tg-47").innerHTML = "47";

    document.getElementById("tg-35").innerHTML =  "35";

}   

Solution

  • The issue is that you have a click event on the full row, on the tr and not on each td.

    What I would do is the following:

    const onClick = (e) => {
      const currentId = e.id;
      e.innerHTML = currentId.replace('tg-', '');
    }
    .td-center {
      text-align: center;
    }
    <table>
      <tr>
        <td class="tg-kpoh td-center">J</td>
        <td id="tg-13" class="td-center" onclick="onClick(this)"><button>?</button></td>
        <td id="tg-10" class="td-center" onclick="onClick(this)"><button>?</button></td>
        <td id="tg-45" class="td-center" onclick="onClick(this)"><button>?</button></td>
        <td id="tg-47" class="td-center" onclick="onClick(this)"><button>?</button></td>
        <td id="tg-35" class="td-center" onclick="onClick(this)"><button>?</button></td>
      </tr>
    </table>

    I did additional improvements just like:

    1. Created td-center class instead of inline styling.
    2. Refactored the onClick event what you had.

    I hope this helps!