Home > front end >  How to update a variable in EJS from the JS script located in the same file?
How to update a variable in EJS from the JS script located in the same file?

Time:03-27

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

<span ><% var i = 0 %></span>
<div ></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?

CodePudding user response:

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  data-increment="0" id="increment"></span>
<div ></div>

You can also assign value like this:

 <span  data-increment="<%= anyValue %>" id="increment"></span>
  • Related