0

I need to add multiple select drop down list in a JSP page, save multiple values into a database in single field, and get a multi-select to display "selected" values when returning to the JSP page.

How is that possible? I am able to save the multiple selected value in a variable, but am not able to save it in a table.

Any help is appreciated in advance.

function AssetDistribution() {
}

function getMultiSelectValue(select) {
  return [].reduce.call(select.options, function(values, option) {
    option.selected ? values.push(option.label) : null;
    return values;
  }, []);
}

function showValues(values) {
  document.forms[0].custom2.value = values.join(' , ');
}
<select id="custom2" name="custom2" multiple="multiple" runat="server" onchange="AssetDistribution();showValues(getMultiSelectValue(this));">
  <option label="PC" id='asset0' value="1000">PC</option>
  <option label="Laptop" id='asset1' value="1200">Laptop</option>
  <option label="Microsoft office" id='asset2' value="140">MS office</option>
  <option label="Software" id='asset3' value="0">Software</option>
  <option label="MSDN" id='asset4' value="2400">MSDN</option>
  <option label="Mac laptop" id='asset5' value="1900">Mac laptop</option>
  <option label="No" id='asset6' value="0">No</option>
  <html:text styleClass="verdana9bld" property="custom2"  size="10" disabled='true'/>
</select>
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
T. Yasir
  • 3
  • 4
  • 1
    Post your Java side code as well, also let us know what's the issue while saving. How do you want to save each selected value? Either each row per value or store all the values in single row? – Vinoth Krishnan Sep 08 '17 at 05:42
  • Hi, Thanks for help, I want save all values in a single row and when i return to the page all values should be display as selected in page. Let me try your below code.. I return to you with the result. Thanks again – T. Yasir Sep 08 '17 at 10:36
  • Yeah, then you can use the below code. To return the values again add `request.setAttribute("selectedAssets",assets);` before redirecting it to jsp page. Then you can get the selected assets values using `${selectedAssets}` parameter. Updated in answer. – Vinoth Krishnan Sep 08 '17 at 10:45
  • Hi, Someone told me i have to create a separate table to save values for multiple selected values. If i keep values comma separated in single row it cannot be displayed as selected when we return to the page. Please advise. I really need help for this. – T. Yasir Sep 08 '17 at 15:55
  • It's not necessary. Comma separated values can be taken from database and iterate in java/JavaScript. You can JavaScript to show the selected values. – Vinoth Krishnan Sep 09 '17 at 04:09
  • How to return comma separated values in drop down to show selected values. I saved comma separated vales in field when i get back to page drop down selected values are blank as it doesn't match any drop down listed value ? I dont wanna change anything in Java files (if possible). – T. Yasir Sep 09 '17 at 14:09
  • My concern is still you've not posted any of your java code. Without seeing your code we can't proceed further. Do you able to get the `selectedAssets` request attribute in your jsp page? – Vinoth Krishnan Sep 11 '17 at 05:56
  • Please find my updated answer with JS code. Mark it as answer/do upvote if it helped you to resolve issue. – Vinoth Krishnan Sep 11 '17 at 07:45
  • Hi Vinoth, Thank you so much to help me here. I dont have direct access to Java files thats why its getting late. Please give me some time i try all code and get back to you. – T. Yasir Sep 11 '17 at 20:35
  • I ahve one more quick question if dont mind. I am getting "code too large for try statement catch" error when in jsp file. how to fix this. In future i may need to add more code on the page also i cannot reduce code, any permanent solution? – T. Yasir Sep 11 '17 at 20:36
  • Read [code too large for try block](https://stackoverflow.com/questions/6904117/code-too-large-for-try-block) for more details about it. – Vinoth Krishnan Sep 12 '17 at 05:20
  • if user select No Asset then how possible selection can’t be combined with any other values and if other values are selected then NO Asset option cant be selected. – T. Yasir Sep 12 '17 at 20:29
  • Hi Vinoth, I have fixed issue with setList.trim().indexOf("A") >= 0 property. I am not understating how to fix code too large issue. Can you please explain ? – T. Yasir Sep 14 '17 at 14:32
  • As the above link says, you can have max of 64kb data in your jsp page. It can't load or performance will be very poor when you try with max data in your page. I came across the same situation in one of my project. We ended up with logically segregating the page to reduce the load. – Vinoth Krishnan Sep 15 '17 at 05:21
  • Yes, code size is crossing the limit and there are chances of add more code in future. How can i split my jsp page? I read on internet to make separate page and add its link with – T. Yasir Sep 15 '17 at 13:30

1 Answers1

0

Since you're adding selected values in array, I assumed that you're going to store all the values in a single column as comma separated values. If so, you can use the below piece of code.

This code can be used in servlet,

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String[] assets = request.getParameterValues("custom2");
    try {
        //For MS SQL Server connection
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        //Provided default port and username, password
        Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks",
                "root", "root");    
        Statement st = conn.createStatement();
        st.executeUpdate("insert into Table_Name(Column_Name) values('" + assets + "')");
        stmt.close();       
        con.close();
        request.setAttribute("selectedAssets", assets); // Will be available as ${selectedAssets} in JSP
        request.getRequestDispatcher("/WEB-INF/home.jsp").forward(request, response);
        } catch (Exception e) {
             e.printStackTrace();
     }
}

And in web.xml. Assumed servlet name is myServlet (you can give your value),

<servlet>
  <servlet-name>myServlet</servlet-name>
  <servlet-class>myServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>myServlet</servlet-name>
  <url-pattern>/myServlet</url-pattern>
</servlet-mapping>

Edit:

Please find the updated script to pre-select the dropdown with values coming from request.

// Get the values from request and store it in JS array
var valArray = [1000,1900];
//Pass the element and array to the function.
setSelectedIndex(document.getElementById("custom2"),valArray);

//Function which selects the given array on page loading.
function setSelectedIndex(s, arr){
    for(i=0; i<s.length; i++){
        for(j=0; j<arr.length; j++){
            if(s[i].value == arr[j]){
               s.options[i].selected = true;
            }
        }
    }
  return;
}

Please find the Working Demo

Let me know if this helps.

Cheers..!

Vinoth Krishnan
  • 2,925
  • 6
  • 29
  • 34