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?
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>