Search code examples
jqueryhtmljspjscript

edit and delete links in table based on if statement


I have the following code, it displays existing sets of cards for a table top game and allows you to edit or delete them. I would like to only allow edit and delete on sets with a weight greater than 100 and display "adminonly" for those that are locked (weight less than 100). is there a simple way to do this, I can provide the full page code if necessary

    <h2>Existing card sets</h2>
<table style="1px solid black">
  <thead>
    <tr>
      <th>Name</th>
      <th>Delete</th>
      <th>Edit</th>
      <th>Weight</th>
      <th>Active</th>
    </tr>
  </thead>
  <tbody>
    <%
      for (PyxCardSet cardSet : cardSets) {
    %>
      <tr>
        <td><%=cardSet.getName()%></td>
        <td><a href="?delete=<%=cardSet.getId()%>" onclick="return confirm('Are you sure?')">Delete</a></td>
        <td><a href="?edit=<%=cardSet.getId()%>">Edit</a></td>
        <td><%=cardSet.getWeight()%></td>
        <td><%=cardSet.isActive()%></td>
      </tr>
    <%
      }
    %>
  </tbody>
</table>

Solution

  • you simple inject the if statement inside the loop and it will do what you are looking for

    <tbody>
        <%
          for (PyxCardSet cardSet : cardSets) {
        %>
          <tr>
            <td><%=cardSet.getName()%></td>
            <% if(cardSet.getWeight()>100) { %>
            <td><a href="?delete=<%=cardSet.getId()%>" onclick="return confirm('Are you sure?')">Delete</a></td>
            <td><a href="?edit=<%=cardSet.getId()%>">Edit</a></td>
            <% } else { %>
             <td>for admin only</td>
            <td>for admin only </td>
            <% } %>
            <td><a href="?edit=<%=cardSet.getId()%>">Edit</a></td>
            <td><%=cardSet.getWeight()%></td>
            <td><%=cardSet.isActive()%></td>
          </tr>
        <%
          }
        %>
      </tbody>
    

    i suggest you to use the JSTL expression language , it's not favorable to have JAVA code inside your JSP . see this it may be helpful