Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
How to update a variable in EJS from the JS script located in the same file?

As stated in the titled, I have this variable 'i' in the scriplet tags of the ejs part:

<span class="UTXOindex"><% var i = 0 %></span>
<div class="test"></div>

and I have the below in the JS script part in the same file with the hopes of being able to increment the above variable:

<script>
      document.getElementById("nextButton").addEventListener("click", e => {
        e.preventDefault()
        document.querySelector(".test").insertAdjacentHTML(
          "afterbegin",
          `
          <p>The number was <%= i %></p>
          <% i++ %>
          <p>The number is now <%= i %></p>
        `
        )
      })
</script>

I am trying to update the variable 'i' in the ejs part from the JS script part but it doesn't seem to update after triggering the event listener multiple times. Triggering the .addEventListener a few times would look like the below:

The number was 0

The number is now 1

The number was 0

The number is now 1

The number was 0

The number is now 1

I was hoping for the below output:

The number was 0

The number is now 1

The number was 1

The number is now 2

The number was 2

The number is now 3

and so on so forth...

Any suggestions? And how to permanently update a variable in EJS scriplet tags?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use HTML data attribute.

 document.getElementById("nextButton").addEventListener("click", e => {
          e.preventDefault()
          var i = Number(document.getElementById("increment").getAttribute("data-increment")) 
          document.querySelector(".test").insertAdjacentHTML(
            "afterbegin",
            `
            <p>The number was ${i}</p>
            <p>The number is now ${i+1}</p>
          `
          )
          document.getElementById("increment").setAttribute("data-increment", i+1);
        })
<button id="nextButton">Click</button>
<span class="UTXOindex" data-increment="0" id="increment"></span>
<div class="test"></div>

You can also assign value like this:

 <span class="UTXOindex" data-increment="<%= anyValue %>" id="increment"></span>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda