Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!