如何使用html dom获取javascript中的复选框cheked值

时间:2015-05-08 09:32:50

标签: javascript html jsp checkbox

基本上我有一个复选框列表,从数据库中检索数据并将其存储在矢量中以循环它。现在我需要获取选择(检查)的值并将其带到另一个jsp用于某种目的,我可以知道如何制作它?当我在javascript中提醒时,我得到“未定义”值。任何帮助,将不胜感激。感谢

First.jsp

<%
Vector vFruit_code        = new Vector();
Vector vFruit_descp       = new Vector();   

DB_FRUIT.makeConnection();
String SQL  = "SELECT * FROM TB_FRUIT WHERE TYPE='FC' WITH UR";
DB_FRUIT.executeQuery(SQL);
while(DB_FRUIT.getNextQuery())
{
    String FRUIT_CODE = DB_FRUIT.getColumnString("VALUE1");
    String FRUIT_DESCP= DB_FRUIT.getColumnString("VALUE2");

     vFruit_code.addElement(FRUIT_CODE);
     vFruit_descp.addElement(FRUIT_DESCP);
}
DB_FRUIT.takeDown();  
%>
<html>
<head>
<script language="Javascript">
 function fnCalulate()
 {

    document.getPremium.FRUIT_CODE.value    = document.mainform.FRUIT_CODE.value;
    document.getPremium.submit();

    // this part i i get undefined value when i try to alert
    alert(document.mainform.FRUIT_CODE.value);
 }
</script>
</head>
<body>
<form name="mainform" method="post" action="pop_fruit_route.jsp">
<table>
        <tr>
        <td>  
              <%
                for (int i=0;i<vFruit_code.size();i++)
                {
                      String sCODE = (String) vFruit_code.elementAt(i);
                      String sDESCP = (String) vFruit_descp.elementAt(i);
               %>
              <input name="FRUIT_CODE" type="checkbox" id="<%=sCODE%>" value="<%=sCODE%>" onclick="fnCalulate();"><%= sDESCP %>
          <%}%>
        </td>  
        </tr>
</table>
</form>
<form name="getPremium" method="post" action="home/calculation/calFruit.jsp">
<input type="hidden" name="FRUIT_CODE">
</form>
</body>
</html>

我需要从检查项目的复选框中获取值到calFruit.jsp

String[] ID = request.getParameterValues("FRUIT_CODE");

输出 enter image description here

1 个答案:

答案 0 :(得分:0)

With what you show, this will fail:

document.getPremium.FRUIT_CODE.value    = document.mainform.FRUIT_CODE.value;

because there is no FRUIT_CODE in getPremium.

If you have multiple checkboxes, you can't say document.mainform.FRUIT_CODE.value; FRUIT_CODE will return an array of all your fruit input tags. you can loop over them and get the value for one that is checked, like:

for (var i = 0; i < document.mainform.FRUIT_CODE.length; ++i ) {
    if (document.mainform.FRUIT_CODE[i].checked)
        document.getPremium.FRUIT_CODE.value = document.mainform.FRUIT_CODE[i].value;
}
alert(document.getPremium.FRUIT_CODE.value);

(though it isn't at all clear to me what you want to happen when multiple ones are checked)

or pass your function the element that was clicked, by changing the call to be:

onclick="fnCalculate(this)"

and the function to:

function fnCalculate(clicked_element) {
    document.getPremium.FRUIT_CODE.value = clicked_element.value;
}

though either way you probably want to decide what should happen when a click unchecks a checkbox.

Note that using a library such as jquery makes everything much easier.