我将对象列表从servlet传递给JSP。在JSP页面上显示它们,如
<c:forEach items="${plcContacts}" var="contact">
<tr>
<td><input type="checkbox" name="contacts" class="case" id ="${contact.col2}" >></input><br></td>
<td>${contact.col5}</td>
<td>${contact.col4}</td>
<td class="teamFunction">${contact.col2}</td>
</tr>
</c:forEach>
在上面,
contact.col5 is email id,
contact.col4 is name,
contact.col2 is team member function.
所以我有按钮选择所有联系人,取消选择所有联系人,联系人根据他们的功能。我已成功使用JQuery,如下所示。
// add multiple select functionality
$("#CheckAll").click(function () {
$('.case').prop('checked', true);
});
$("#UnCheckAll").click(function () {
$('.case').prop('checked', false);
});
// check by Function
$("#CheckByFunction").click(function() {
$('input[type=checkbox]').each(function () {
var plc = $('#plcFunction').val().replace(/ /g, '-');
var teamFunction = this.id.replace(/ /g, '-');
if (plc == teamFunction) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
});
});
我的问题是,当在这个JSP页面上单击下一个按钮时,我需要将其复选框选中的联系人对象列表发送到servlet。我想尝试如下。
**//read all the checked contacts**
$("#Next").click(function() {
selected = new Array();
$("input[type='checkbox']:checked").each(function() {
selected.push($(this).val());
});
});
我可以通过将它们放入会话中来检索servlet中的所有联系对象,但我只需要选中具有复选框的联系人。有人可以帮我这个吗?
答案 0 :(得分:1)
您需要为复选框指定一个唯一值,用于标识选中的值:
<input type="checkbox" name="contacts" value="${contact.col2}" />
然后您可以使用HttpServletRequest#getParameterValues()
获取所有选中的值:
String[] checkedContacts = request.getParameterValues("contacts");
这就是全部。无需在提交时将其收集到某些JS数组中。这是一个丑陋的JS黑客,它不会优雅地降级(即如果最终用户已禁用JS,则整个提交会中断)。
答案 1 :(得分:0)
首先,你的html需要一个值属性集,而不是id:
<c:forEach items="${plcContacts}" var="contact">
<tr>
<td><input type="checkbox" name="contacts" class="case" value="${contact.col2}"></input></td>
</tr>
</c:forEach>
其次,你的javascript应该是以下内容:
$("#CheckAll").click(function () {
//Notice use of attr here, not prop
$('.case').attr('checked', true);
});
$("#UnCheckAll").click(function () {
//notice we are remove attr
$('.case').removeAttr('checked');
});
//should be able to complete the fill by function based off the above
//to get the selected, you weren't far off, biggest thing should actually be
//the setting of value instead of id.
var selected = [];
$("input[type='checkbox']:checked").each(function() {
selected.push($(this).val());
});
//spit the array out so you can see what you end up with.
console.log(selected)
答案 2 :(得分:0)
好吧,您将undefined
值存储在数组中,因为您的复选框没有value
属性,而且您的标记无效,input
元素没有关闭{{1 }}},假设您的输入有以下类,您可以使用</input>
方法并将值存储在数组中。
map