如何检查我的jsp中是否选中了至少一个复选框?

时间:2013-06-10 07:49:03

标签: javascript jsp checkbox

这是jsp,显示我的资金表中的所有细节,然后给出一个chekbox删除任何一个..但现在我想添加一个javascript来检查是否至少检查了一个复选框,以便一个db调用不是浪费...

<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Deleting Funds</title>
<script type="text/javascript">
var checkForm = function(form){
var inputs = form.getElementsByTagName('input');
for(var i = 0, l = inputs.length; i < l; i++){
    var input = inputs[i];
    if(input.type == "checkbox" && input.checked)
            return true;
    }
    alert('none are checked');
    return false;
};
</script>
</head>
<body>
<%
  Enumeration names = request.getParameterNames();
  while (names.hasMoreElements()) {
  String name = (String) names.nextElement();
  StringBuffer sb = new StringBuffer(name);
      com.mini.funds.Admin.Delete(sb.toString());
  }

%>
<br>

<div class="navigator">
<a href="index.html">Add</a>
<a id="currenttab" href="delete.jsp">Delete</a>
<a href="update.jsp">Update</a>
</div>

<br> <br> <br>

<form action="deleteFunds.jsp" method="post" onsumbit="return checkForm(this);">
<table>
<tr>
<th>code</th>
<th>name</th>
<th>type</th>
<th>nav</th>
<th>min_holdings</th>
<th>desription</th>
<th>terms</th>
<th>check</th>
</tr> 
<%

 ArrayList<MutualFund> al = com.mini.funds.Admin.GetFunds();
      String id;
  String box = null;
  int num = al.size();
  int i=0;
   while(i<num)
  {
MutualFund  almf = al.get(i);
out.print("<tr>");
      out.print("<td>");
      String code = almf.getMf_code();
      out.print(code);
      out.print("</td>");

      out.print("<td>");
     String x = almf.getMf_name();
      out.print(x);
      out.print("</td>");

      out.print("<td>");
      String y = almf.getMf_type();
     out.print(y);
     out.print("</td>");

     out.print("<td>");
     int a = almf.getNav();
    out.print(a);
    out.print("</td>")
    ;
    out.print("<td>");
     int b = almf.getMf_min_holdings();
   out.print(b);
   out.print("</td>");

       out.print("<td>");
       String z = almf.getMf_description();
      out.print(z);
      out.print("</td>");

      out.print("<td>");
      String l = almf.getMf_TandC();
     out.print(l);
     out.print("</td>");

  out.print("<td>");
  box = "<input name=" + code + " type='checkbox'>";
  out.print(box);
  out.print("</td>");
  out.print("</tr>");
  i++;
 }
%>

</table>

<br>
<input type="submit" value="Delete">
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要做的就是遍历表单中的所有输入标记,检查复选框和检查的标记。如果找到,请正常提交表格。如果找不到,请通过返回false取消提交表单。

示例功能:

var checkForm = function(form){
    var inputs = form.getElementsByTagName('input');
    for(var i = 0, l = inputs.length; i < l; i++){
        var input = inputs[i];
        if(input.type == "checkbox" && input.checked)
            return true;
    }
    alert('none are checked');
    return false;
};

它可以在表格的onsubmit中调用:

onsumbit="return checkForm(this);"

演示:http://jsfiddle.net/QZPYG/