我使用以下代码来处理 html 按钮事件:
if(request.getParameter("btnSubmit")!=null)
我使用以下代码来捕获具有相同名称(“选择”)的选定复选框:
String[] selecttype = request.getParameterValues("choices");
if (selecttype != null && selecttype.length != 0)
{
for (int i = 0; i < selecttype.length; i++)
{
out.println("<h4><font color = 'red'>" + selecttype[i] + "</font></h4>");
}
}
问题是,在按下提交按钮之前,所选复选框的值会显示在屏幕上。但是,当按下“提交”按钮时,这些值就消失了。有什么帮助吗?!
最佳答案
您需要某种逻辑来设置 checked
根据捕获的选择在复选框中添加属性(即勾选之前选择的复选框)。我建议您将表单提交给一个中间 Servlet,负责处理捕获的选择,将它们存储到比字符串数组更合适的数据结构中,并将请求转发回您的 jsp 页面,这也将使业务逻辑与看法。
无论如何,如果您确实需要在没有中间 Servlet 的情况下重新提交到同一页面,这里有一个懒惰的方法来处理 checked
属性:
<%
// Put this scriptet before your checkboxes
String[] choiceArray = request.getParameterValues("choices");
// avoids NPEs
Set<String> capturedChoices = new HashSet<String>();
if (choiceArray != null) {
capturedChoices = new HashSet<String>(Arrays.asList(choiceArray));
}
%>
并在您的复选框渲染代码中:
<input type="checkbox" name="choices" value="choice1"
<%= capturedChoices.contains("choice1") ? "checked=\"checked\"" : "" %> />
<input type="checkbox" name="choices" value="choice2"
<%= capturedChoices.contains("choice2") ? "checked=\"checked\"" : "" %> />
<!-- And so on (replace `choice1`, `choice2`, etc with actual values). -->
当然,有比 Set<String>
更合适的数据结构来保存捕获的选择。 (例如, boolean[]
或 Map<String, Boolean>
),但这应该让您了解必须做什么。
关于java - HTML 按钮事件和选定的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16322396/