简体   繁体   中英

How to get the values of a dropdown multi select list in a JSP page

I created a dropdown multi select list using javascript function which is as follows

function addRow() {

                    $(function() {
                        $('#lstFruits').multiselect({
                            includeSelectAllOption : true
                        });
                    });

                    var table = document.getElementById('my_table'); //html table
                    var rowCount = table.rows.length; //no. of rows in table
                    var columnCount = table.rows[0].cells.length; //no. of columns in table          
                    var row = table.insertRow(rowCount); //insert a row            

                    var cell1 = row.insertCell(0); //create a new cell           
                    var element1 = document.createElement("input"); //create a new element           
                    element1.type = "checkbox"; //set the element type 
                    element1.setAttribute('id', 'newCheckbox'); //set the id attribute   
                    element1.setAttribute('checked', true); //set checkbox by default checked  
                    cell1.appendChild(element1); //append element to cell

                    var cell2 = row.insertCell(1);
                    var element2 = document.createElement("input");
                    element2.type = "text";
                    element2.setAttribute('id', 'newInput'); //set the id attribute
                    element2.setAttribute('name', 'sl' + rowCount);
                    element2.setAttribute('style', 'width: 50px');
                    cell2.appendChild(element2);

                    var cell3 = row.insertCell(2);
                    var element3 = document.createElement("input");
                    element3.type = "textarea";
                    element3.setAttribute('rows', '4');
                    element3.setAttribute('cols', '40');
                    element3.setAttribute('id', 'newInput'); //set the id attribute
                    element3.setAttribute('name', 'discription' + rowCount);
                    cell3.appendChild(element3);

                    var cell4 = row.insertCell(3);
                    var element4 = document.createElement("input");
                    element4.type = "text";
                    element4.setAttribute('id', 'newInput'); //set the id attribute
                    element4.setAttribute('name', 'quantity' + rowCount);
                    cell4.appendChild(element4);

                    var cell5 = row.insertCell(4);
                    var element5 = document.createElement("input");
                    element5.type = "text";
                    element5.setAttribute('id', 'newInput'); //set the id attribute
                    element5.setAttribute('name', 'price' + rowCount);
                    cell5.appendChild(element5);

                    var cell6 = row.insertCell(5);
                    var element6 = document.createElement("input");
                    element6.type = "text";
                    element6.setAttribute('id', 'newInput'); //set the id attribute
                    element6.setAttribute('name', 'CST' + rowCount);
                    element6.setAttribute('style', 'width: 50px');
                    cell6.appendChild(element6);

                    var cell7 = row.insertCell(6);
                    var element7 = document.createElement("select");
                    element7.type = "select";
                    element7.setAttribute('multiple', 'multiple');

                    //  element7.setAttribute('style', 'width: 50px');

                    element7.setAttribute('size', 3);
                    element6.setAttribute('id', 'newSelect'); //set the id attribute
                    element6.setAttribute('name', 'taxGroup' + rowCount);

                    var option1 = document.createElement("option");
                    var option2 = document.createElement("option");
                    var option3 = document.createElement("option");
                    var option4 = document.createElement("option");
                    var option5 = document.createElement("option");
                    var option6 = document.createElement("option");
                    var option7 = document.createElement("option");
                    var option8 = document.createElement("option");
                    option1.text = "Select Tax";
                    option2.text = "VAT5";
                    option3.text = "VAt14.5";
                    option4.text = "SALES TAX";
                    option5.text = "SERVICE TAX";
                    option6.text = "KISHI Kalyan";
                    option7.text = "Swachh BHARAT";
                    option8.text = "GST";

                    element7.add(option1);
                    element7.add(option2);
                    element7.add(option3);
                    element7.add(option4);
                    element7.add(option5);
                    element7.add(option6);
                    element7.add(option7);
                    element7.add(option8);
cell7.appendChild(element7);
}

Now my question is:

How to get the selected values to another jsp page.

I tried the code but the code is not working well.

So i am posting the code so that if any changes required you can say to me.

The code is as follows

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="com.model.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.DecimalFormat"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%
        String organizationName, phoneNo, buyDate, invoiceNo, buyerOrderNo, esugamNo, deliveryAddress, PANNo, deliveryNote, invoiceDate, termsofPayment, dispatchDocumentNo, attention, dated, dispatchThrough, destination, termsOfDelivery, discount, buyerTin, buyerCSTNo;
            int CId =0;
            organizationName = request.getParameter("bname");
            phoneNo = request.getParameter("bno");
            buyDate = request.getParameter("buyerorderDate");
            invoiceNo = request.getParameter("invNo");
            buyerOrderNo = request.getParameter("buyerOrderNo");
            esugamNo = request.getParameter("esugamNo");
            PANNo = request.getParameter("bpan");
            deliveryNote = request.getParameter("delivNote");
            invoiceDate = request.getParameter("invoiceDate");
            attention = request.getParameter("bAttn");
            dated = request.getParameter("dispatchDate");
            dispatchThrough = request.getParameter("dispThrough");
            destination = request.getParameter("destination");
            termsOfDelivery = request.getParameter("termDelivery");
            discount = request.getParameter("discount");
            buyerTin = request.getParameter("bTinNo");
            buyerCSTNo = request.getParameter("bcstNo");
            deliveryAddress = request.getParameter("bDelivAdd");
            termsofPayment = request.getParameter("termsOfPmnt");
            dispatchDocumentNo = request.getParameter("dispDocNo");

            try{
        DBConnect db =new DBConnect();
        Connection con = db.getCon();
        String sql ="insert into marketing_database.invoiceclient_details (OrganizationName,PhoneNo,BuyDate,InvoiceNo,BuyerOrderNo,EsugamNo,DeliveryAddress,PANNO,DeliveryNote,InvoiceDate,TermsOfPayment,DispatchDocumentNo,DispatchThrough,Destination,TermsofDelivery,Attention,Discount,BuyerTin,BuyerCSTNo,Dated) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
        PreparedStatement  ps =con.prepareStatement(sql);
        ps.setString(1, organizationName);
        ps.setString(2, phoneNo);
        ps.setString(3, buyDate);
        ps.setString(4, invoiceNo);
        ps.setString(5, buyerOrderNo);
        ps.setString(6, esugamNo);
        ps.setString(7, deliveryAddress);
        ps.setString(8, PANNo);
        ps.setString(9, deliveryNote);
        ps.setString(10, invoiceDate);
        ps.setString(11, termsofPayment);
        ps.setString(12, dispatchDocumentNo);
        ps.setString(13, dispatchThrough);
        ps.setString(14,destination );
        ps.setString(15, termsOfDelivery);
        ps.setString(16, attention);
        ps.setString(17, discount);
        ps.setString(18, buyerTin);
        ps.setString(19, buyerCSTNo);
        ps.setString(20, dated);

        ps.executeUpdate();

        //Get Max CID
        String sql1 ="Select MAX(CId) from marketing_database.invoiceclient_details";
        PreparedStatement ps1 = con.prepareStatement(sql1);
        ResultSet rs  =ps1.executeQuery(sql1);
        while(rs.next())
        {
            CId =rs.getInt(1);
            System.out.println("CId====="+CId);
        }
        con.close();
        ps.close();
        ps1.close();
        rs.close();
        System.out.println("Saved to Invoice Details");
            }
            catch(SQLException ex){
        ex.printStackTrace();
            }

            //
            String createdBy=(String)session.getAttribute("email");

            String row = request.getParameter("rowCount");   
            System.out.println("Row Count====="+row);
            int rowCount = Integer.parseInt(row);


            String item,description;
            String CST;
            int quantity;
            double perUnitPrice;

              String serviceTax =null, vat5 = null, vat14 = null;

              try{
          DBConnect db =new DBConnect();
          Connection con = db.getCon();
                String sql = " select vat5,vat14,serviceTax FROM marketing_database.tax_info WHERE id='1' ;";
                PreparedStatement ps = con.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                vat5 = rs.getString("vat5");
                vat14 = rs.getString("vat14");
                serviceTax = rs.getString("serviceTax");
               // CST = rs.getString("CST");
            }
            con.close();
            ps.close();
            rs.close();
              }
              catch(SQLException ex){
          ex.printStackTrace();
              }
         int j=1;


         List<Double> cstAmountList= new ArrayList<Double>();
         List<Double> vat5AmountList= new ArrayList<Double>();
         List<Double> vat14AmountList= new ArrayList<Double>();
         List<Double> svcTaxAmountList= new ArrayList<Double>();

         while (j < rowCount) {

        float serviceTaxDB = 0, vat5DB = 0, vat14DB = 0;

        description = request.getParameter("discription" + j);


         if(request.getParameter("quantity" + j)==null ||request.getParameter("quantity" + j).equals(""))
            {
                quantity=0;
            }
            else{
                quantity = Integer.parseInt(request.getParameter("quantity" + j));
            }

            if(request.getParameter("price"+ j)==null ||request.getParameter("price"+ j).equals(""))
            {
                perUnitPrice=0;
            }
            else{
                perUnitPrice = Double.parseDouble(request.getParameter("price"+ j));
            }



//      quantity = Integer.parseInt(request
//              .getParameter("quantity" + j));

//      perUnitPrice = Double.parseDouble(request.getParameter("price"+ j));

        double totalPrice = (quantity*perUnitPrice);

        CST =request.getParameter("CST"+ j);
        float cst;
        if(CST==null ||CST=="")
        {
             cst=0;
        }
        else{
             cst=Float.parseFloat(CST);
        }

              double cstAmnt=0,vat5Amnt=0,vat14Amnt=0,serviceTaxAmnt=0;


               cstAmnt = (totalPrice*cst)/100;
               //rounding to two decimal places
               DecimalFormat cstroundoff = new DecimalFormat("0.00");
               String cstround = cstroundoff.format(cstAmnt);
               double cstroundofff = Double.parseDouble(cstround);
               cstAmountList.add(cstroundofff);


             // Get Selected TAX from MultiSelct DropDown List  

                  int length =0;
                  String[] tax = request.getParameterValues("taxGroup" + j);
                  length =tax.length;
                 for(int i=0;i<length-1;i++){
                     String taxName=tax[i];
                     System.out.println("Tax Name is = "+taxName);
                 }
                  if(tax==null ||tax.equals(""))
                  {
                      length=0;
                  }
                  else{
                      length = tax.length;

                  }

//                String[] tax;

//                tax = request.getParameterValues("tax" + j);
//                int length = tax.length;
              //  System.out.println("length===="+length);
                  if (tax != null) {
                      for (int k = 0; k < tax.length; k++) {
                          if (tax[k].contains("vat5")) {

                             vat5DB = Float.parseFloat(vat5);
                              vat5Amnt = (totalPrice*vat5DB)/100;
                               // rounding to two decimal places

                              DecimalFormat vat5roundoff = new DecimalFormat("0.00");
                              String vat5round = vat5roundoff.format(vat5Amnt);
                              double vat5roundofff = Double.parseDouble(vat5round);
                              vat5AmountList.add(vat5roundofff);
                          }
                          if (tax[k].contains("vat14")) {

                            vat14DB =Float.parseFloat(vat14) ;
                            vat14Amnt = (totalPrice*vat14DB)/100;
                            //rounding to two decimal places
                            DecimalFormat vat14roundoff = new DecimalFormat("0.00");
                            String vat14round = vat14roundoff.format(vat14Amnt);
                            double vat14roundofff = Double.parseDouble(vat14round);
                            vat14AmountList.add(vat14roundofff);
                          }
                          if (tax[k].contains("serviceTax")) {

                             serviceTaxDB = Float.parseFloat(serviceTax);
                              serviceTaxAmnt = (totalPrice*serviceTaxDB)/100;
                              //rounding to two decimal places
                              DecimalFormat svcroundoff = new DecimalFormat("0.00");
                              String svcround = svcroundoff.format(serviceTaxAmnt);
                              double svcroundofff = Double.parseDouble(svcround);
                              svcTaxAmountList.add(svcroundofff);
                          }

//                        if (tax[k].contains("cst")) {

//                           CSTDB =Float.parseFloat(CST);

//                        }
                      }
                  } 
                  try{
                      DBConnect db =new DBConnect();
                      Connection con = db.getCon();
                      String sql ="INSERT INTO marketing_database.invoice (CId,CreatedBy,DescriptionOfGoods,Quantity,PerUnitPrice,VAT5,VAT14,ServiceTax,CST,TotalPrice) values (?,?,?,?,?,?,?,?,?,?);";
                      PreparedStatement ps = con.prepareStatement(sql);
                      ps.setInt(1, CId);
                      ps.setString(2, createdBy);
                      ps.setString(3, description);
                      ps.setInt(4, quantity);
                      ps.setDouble(5, perUnitPrice);
                      ps.setDouble(6, vat5Amnt);
                      ps.setDouble(7, vat14Amnt);
                      ps.setDouble(8, serviceTaxAmnt);
                      ps.setDouble(9, cstAmnt);
                      ps.setDouble(10, totalPrice);
                      ps.executeUpdate();
                      System.out.println(" Saved to invoicing !!");
                     con.close();
                     ps.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }

            j = j + 1;

        }
           double subTotal =0.0;
           double cstTotal =0.0;
           double vat5Total= 0.0;
           double vat14Total = 0.0;
           double svcTaxTotal =0.0;
         try{
             DBConnect db =new DBConnect();
              Connection con = db.getCon();
                    String sql = "select SUM(TotalPrice) FROM marketing_database.invoice WHERE CId='"+CId+"' ;";
                    PreparedStatement ps = con.prepareStatement(sql);
                    ResultSet rs = ps.executeQuery();
                    while(rs.next()){
                        subTotal=rs.getDouble(1);

                    }
                    int cstSize = cstAmountList.size();
                   System.out.println("CST size==="+cstSize);
                    for(int i=0;i<cstSize;i++)
                    {
                        cstTotal+=cstAmountList.get(i);
                    }
                    int vat5Size =vat5AmountList.size();
                    System.out.println("vat5 size==="+vat5Size);
                    for(int i=0;i<vat5Size;i++)
                    {
                        vat5Total+=vat5AmountList.get(i);
                    }
                    int vat14size = vat14AmountList.size();
                    System.out.println("vat14 size==="+vat14size);
                    for(int i=0;i<vat14size;i++)
                    {
                        vat14Total+=vat14AmountList.get(i);
                    }
                    int svcSize = svcTaxAmountList.size();
                    for(int i=0;i<svcSize;i++)
                    {
                        svcTaxTotal+=svcTaxAmountList.get(i);
                    }

                    Double grandTotal =subTotal+cstTotal+vat5Total+vat14Total+svcTaxTotal;
                    int roundofff = (int) Math.round(grandTotal);
                    String sql1 = "UPDATE `marketing_database`.`invoiceclient_details` SET `SubTotal`=? ,`grandTotal`=? , `cstAmount`=? ,`vat5Amount`=? ,`vat14Amount`=?,`svcTaxAmount`=? WHERE `CId`='"+CId+"';" ;
                    PreparedStatement psmt = con.prepareStatement(sql1);
                    psmt.setDouble(1, subTotal);
                    psmt.setDouble(2, roundofff);
                    psmt.setDouble(3, cstTotal);
                    psmt.setDouble(4, vat5Total);
                    psmt.setDouble(5, vat14Total);
                    psmt.setDouble(6, svcTaxTotal);
                    psmt.executeUpdate();
                    con.close();
                    psmt.close();
                    System.out.println("Sub total updated in Invoice details");
         }
         catch(SQLException ex)
         {
         ex.printStackTrace();
         }
        response.sendRedirect("Ihome.jsp");
    %>
</body>
</html>

请看一下附件

Any help in this will be appreciated

for multi select drop down use:

<select name="ur_name[]"></select>

name="ur_name[]" will make it an array. When its containing form is submitted you will get the selected array like

ur_name[0] = first element, ur_name[1] = second element and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM