0

Does anyone know how to access ejs vars in a script tag?

I'm trying to allow each one of my edit buttons to change the contenteditable attribute on each 'td' in the specific row to true.

The problem I'm having is, I don't know how to access vars from ejs in my script.

What I'm trying to do is:

<script>
    var row = document.getElementById(<$= index %>);
</script>

And then from there, make the rows children with attribute 'contenteditable' set to true. Is this possible? Is there a better way?

Here's all the code I have:

<tr class=<%- index %>>
  <td><%= index %></td>
  <td contenteditable="false" id="item"><%= item %></td>
  <td contenteditable="false" id="desc"><%= desc %></td>
  <td contenteditable="false" id="status"><%= status %></td>
  <td contenteditable="false" id="priority"><%= priority %></td>
  <td><button id="delete-button">Delete</button>
    <button id=<%- index %>>Edit</button>
  </td>
</tr>
<script>
    var row = document.getElementById(<$= index %>);
</script>

And my table:

<table id="todo-list">
      <tr>

        <th>No.</th>
        <th>Item</th>
        <th>Description</th>
        <th>Status</th>
        <th>Priority</th>
        <th>Actions</th>
      </tr>
      <% for (var i = 0; i <data.length; i++) { %>
      <%  const {item, desc, status, priority} = data[i]; %>
      <% (function() { %>
      <%- include('partials/todo.ejs', {index: i, item:item, desc: desc, status:status, priority:priority}) %>
      <% })(); %>
      <%} %>
    </table>
ether
  • 91
  • 5

1 Answers1

1

I believe it is not possible to put ejs variable to inside an already-running script tag. A detailed answer can be found here.

If you wish to just change the cells to contenteditable = true, you could try using this:

<tr>
  <td><%= index %></td>
  <td contenteditable="false" class="editable" id="item">
    <%= item %>
  </td>
  <td contenteditable="false" class="editable" id="desc">
    <%= desc %>
  </td>
  <td contenteditable="false" class="editable" id="status">
    <%= status %>
  </td>
  <td contenteditable="false" class="editable" id="priority">
    <%= priority %>
  </td>
  <td><button id="delete-button">Delete</button>
    <button onclick="editRow(this)">Edit</button>
  </td>
</tr>

<script>
  function editRow(btn) {
    var row = btn.parentNode.parentNode; // This is the row you need
    var cells = row.getElementsByTagName("td");
    for (var i = 0; i < cells.length; i++) {
      if (cells[i].classList.contains('editable')) { //Checks if it is the right cell
        cells[i].contentEditable = true;
      }
    }
  }
</script>

I added the class="editable" to avoid making the first and last cell contenteditable

FurtiveStranger
  • 125
  • 1
  • 10