Express/EJS Help

Hello. I am learning EJS and I’m trying to understand how to make a button that, when clicked, will display a random entry from my DB. So far I have the following code:

<button id="play">Play</button>
<button id="add">Add</button>

<% function getNewCard() { %>
  <% var randomNumber = Math.floor(Math.random() * (cards.length + 1)); %>
  <h1><%= cards[randomNumber].correctAnswer %></h1>
<% } %>

This function will work if I call it normally, but I want it to run when I click the ‘Play’ button. Is this something that is possible or am I approaching this incorrectly?

Maybe catch a click event, something like:
var id = document.getElementById(‘play’);

id.onclick = function() {


Or try this (I’m on mobile, there might be mistakes in code):
button onclick=’<%= getNewCard%>’.

Heres a quicker way:

Change this:

<button id="play">Play</button>

To this:

<button id="play" onClick="getNewCard()">Play</button>

Thank you for your help but I still cannot get it to work. Likely I am doing something else wrong. I have simplified the page into only the following code:

<% function getNewCard() { %>
  <% var randomNumber = Math.floor(Math.random() * (cards.length + 1)); %>
  <h1><%= cards[randomNumber] %></h1>
<% } %>

<button onclick='<% getNewCard() %>'>Click</button>

I have also tried:

<button onclick='<%= getNewCard() %>'>Click</button>

In both cases I get an error and the console shows 'unexpected token < ’ and then shows the error on Line 15. But there is no line 15 so I’m not sure what it is referring too.


Why are you trying to define this in your template file? Put the function in a JS file, bind the event handler like normal, and then link the JS file on your page.

EJS, like other template solutions, should only handle view logic. So, if you want to display the user’s name or loop through an array and create a list of items, EJS makes it easy to do that before the web page has been sent to the user. For this, you’ll want to stick with AJAX.

Thank you for the response. I’m very new to Express/EJS so it appears I have a lot more to learn before I try implementing what I’m trying to do. I’ll attempt this again after I learn a lot more.