How to create table dynamically using count and JS

2020-02-12 12:02发布

问题:

I want to create a dynamic table accepting book attributes when it has provided the no. of books to be entered on the previous page. But I am not getting anything.

This is my code:

<table>
<c:forEach begin="1" end= "${ no }" step="1" varStatus="loopCounter">
<tr>
<td>
<input type='text' name="isbn" placeholder="ISBN">
</td>
<td>
<input type="text" name="Title" placeholder="Title">
</td>
<td>
<input type="text" name="Authors" placeholder="Author">
</td>
<td>
<input type="text" name="Version" placeholder="Version">
</td>
</tr>
</c:forEach>
</table>

${no} is the count of number of books I want to enter. I am new here. Sorry if the title is not clear. Please help.

回答1:

You're not getting anything because you're not iterating your list of books. Also, you're only printing lots of <input type="text" /> on each iteration. Your code should look like this (assuming that your list of books is lstBooks and it's already initialized):

<table>
    <!-- here should go some titles... -->
    <tr>
        <th>ISBN</th>
        <th>Title</th>
        <th>Authors</th>
        <th>Version</th>
    </tr>
    <c:forEach begin="1" end= "${ no }" step="1" varStatus="loopCounter"
        value="${lstBooks}" var="book">
    <tr>
        <td>
            <c:out value="${book.isbn}" />
        </td>
        <td>
            <c:out value="${book.title}" />
        </td>
        <td>
            <c:out value="${book.authors}" />
        </td>
        <td>
            <c:out value="${book.version}" />
        </td>
    </tr>
    </c:forEach>
</table>

After understanding your problem based on comments, make sure the ${no} variable is available at request.getAttribute("no"). You can test this using a scriptlet (but this is a bad idea) or just using <c:out value="${no}" />.

Note that as I've said, the variable should be accesible through request.getAttribute, do not confuse it with request.getParameter.

By the way, you can set a variable if you know which could be it's value like this:

<c:set var="no" value="10" />

And then you can access to it using ${no}.

More info: JSTL Core Tag



回答2:

Suppose You have given a List of map List<Map<String, Object>> underEmployees

<caption>Emplyess Under You</caption>
<tr>
    <th>Employee Id</th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Designation
</tr>
<c:forEach  var="record"  items="${underEmployees}" > 
    <tr>
        <c:forEach var="entry" items= "${record}">
            <th><c:out value="${entry.value}"></c:out></th>
        </c:forEach>

    </tr>
</c:forEach>



标签: jsp foreach jstl