我目前正在使用选择框动态添加表行,并在servlet中获取添加的选择框的值。选择框的添加工作正常,但是当我获得在servlet中动态添加的选择框的值时,值变为null。这是我现在的代码:
使用Javascript:
function addCreditRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var count = rowCount+1;
var cell1 = row.insertCell(0);
var element1 = document.createElement("select");
element1.name = "credAcc"+count; //*** EDIT ***
<%for(int i = 0; i < aList.size(); i++){%>
var option = document.createElement("option");
option.setAttribute("value", "<%=aList.get(i).getAccount_name()%>");
option.innerHTML = "<%=aList.get(i).getAccount_name()%>";
element1.appendChild(option);
<%}%>
cell1.appendChild(element1);
document.getElementById("cred").value=count;
var cell2 = row.insertCell(1);
var element = document.createElement("input");
element.type = "text";
element.name = "credAmt"+count; //*** EDIT ***
cell2.appendChild(element);
}
HTML:
<div class="pull-right">
<INPUT type="button" class="btn btn-default" value="Add A Credit Account" onclick="addCreditRow('credTable')" />
</div>
<input type="hidden" name="credit" id="cred" value="1">
<br><br>
<table class="table">
<thead>
<tr>
<th>Account</th>
<th>Amount</th>
</tr>
</thead>
</table>
<table class="table" id="credTable">
<tbody>
<tr>
<td><select name="credAcc1">
<%for(int i = 0 ; i < aList.size(); i++){%>
<option value="<%=aList.get(i).getAccount_name()%>"><%=aList.get(i).getAccount_name()%></option>
<%}%>
</select></td>
<td><input type="text" name="credAmt1"></td>
</tr>
</tbody>
</table>
Java Servlet:
int credit = Integer.parseInt(request.getParameter("credit"));
ArrayList<String> credList = new ArrayList();
for(int x = 1; x < credit+1; x++){
credList.add(request.getParameter("credAcc"+x));
}
ServletContext context= getServletContext();
request.setAttribute("credList", credList);
RequestDispatcher rd= context.getRequestDispatcher("/newjsp.jsp");
rd.forward(request, response);
我在JSP页面中显示存储在ArrayList中的值:
<%@page import="java.util.ArrayList"%>
<HTML>
<%
ArrayList<String> credList = (ArrayList<String>) request.getAttribute("credList");
%>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
</HEAD>
<BODY>
<form name="myform" action="myServlet" method="post">
<h1>CREDIT ACCOUNTS:</h1><br>
<%for(int i = 0; i < credList.size(); i++){%>
<h2><%=credList.get(i)%></h2><br>
<%}%>
</form>
</BODY>
</HTML>
我的javascript功能有问题吗?
答案 0 :(得分:0)
不完全理解你的问题,但你有意在JSP scriptlet中添加选项,而这些选项没有出现在你的HTML代码中。如果是这种情况,您在addCreditRow函数中创建Options的方式可以这样:
try{
t1.add( new Option( name , value ) );
}catch( e ){
t1.add( new Option( name , value ), null );
}
这样做的目的是尝试使用带有标准两个参数的第一个新运算符创建Option,如果失败,那么对于某些浏览器,它将使用三个参数创建。