views:

112

answers:

2

I want to be able to send all the selected values from a dropdown box (which allows multiple selection) as a hidden field using JQuery. I was able to send/retrieve a single value on form submission.

If anyone can share some code snippet, that would help.

Thanks in Advance!

+2  A: 

Well, it's not so clear what you are really asking for. There is no "multiple selection dropdownlist" in HTML. To have a multiselect you need to specify

<select id="foobar" multiple>

that will create a listbox where you may select multiple elements. Calling

var sel = $('#foobar').val();

will return an Array of selected items.

edit

To get the text from each option, use .map() or jQuery.map(). Example:

var sel = $('#foobar').children('option:selected').map(function(i,e){
    return e.innerText;
}).get();

That will create an Array containing the text of all selected entrys.

jAndy
I meant the listbox, sorry for the typos. The .val() call doesn't give me the text of the selected options as the listbox is a dependent dropdown and consists of a JSON String. So, .val gives me the integer index and not the text. I use the option #3 listed here http://stackoverflow.com/questions/2263996/populating-child-dropdownlists-in-jsp-servlet in order to populate the child dropdown.
gpmattoo
@gpmattoo: I've updated my post, that may help.
jAndy
10 on 10. I am still new here, so was unable to post formatted code in a limited span of time. Not sure if Ctrl+K on comments really works for code formatting or not. FYI.. this was my first attempt at JQuery and am liking it.
gpmattoo
A: 

There's absolutely no need to do like that. You was apparently using request.getParameter() instead of request.getParameterValues() and wondering why it returned only the first value.

Just fix your servlet code accordingly:

String[] selectedItems = request.getParameterValues("dropdownname");

No need for ugly JS/jQuery hacks to send them all as single parameter. In future questions, try to ask how to solve a problem instead of how to achieve a solution which may after all not be the right solution per se.

BalusC