Search code examples
javascriptnode.jswebejsviewengine

How to change value of multiple iterated element in ejs dynamically?


Here is my EJS code: when I click on any iterated button it only changes first element's value. But I want to make other element to change as well. What's wrong with it?

<% for(let i=0; i<10; i++){
    %> <h2 id="value">0</h2>  <button onclick="btnHandler()">click to change</button> </h1> <%
} %>

<script> 
    let val = document.getElementById('value');
    let start = 0
    function btnHandler(){
        val.innerHTML = `${start++}`
    }
</script>

I try to to change value of iterated element using iterated button with onlclick but it only affect first elements. I expect to change other element as well.


Solution

  • In the rendered HTML, you have 10 <h2> elements and 10 <button>s, but there is no correspondence between each <button> and "its" <h2> element. Moreover, all the <h2> elements have the same id, and you have only one start counter whereas you need 10.

    The following solution relates <h2> elements, <button>s and counters by the index i. I assume this is what you intend to achieve.

    <% for(let i=0; i<10; i++){
        %> <h2 id="value-<%= i %>">0</h2>  <button onclick="btnHandler(<%= i %>)">click to change</button> <%
    } %>
    <script> 
    let start = [];
    function btnHandler(i){
      start[i] = start[i] || 0;
      let val = document.getElementById('value-' + i);
      val.innerHTML = ++start[i];
    }
    </script>