Have a potentially infinite collection of drop downs, giving them all the same class, need to be able to access, loop through, and collect the selected value on the option of all the drop downs regardless of how many there could be. The final form should be something like 5,6,7,6,4,2,3,4,3,4 as a comma delimited list of the selected values from all drop downs.
views:
52answers:
1
+1
A:
var ids = $("select.classname > option:selected").map(function(n, i) {
return $(n).val();
}).join(",");
To explain what that's doing:
- Firstly it selects all the selected options within the given drop downs (identified by "classname");
- It passes every selected option to a callback function;
- That callback function returns the value of the selected option;
- Because you called map on the array of selected options, you've now got an array of values using the
map()
method; - The
join()
function transforms that array into a comma delimited list.
For example:
<select class="classname">
<option value="1">One</option>
<option value="2" selected>Two</option>
<option value="3" selected>Three</option>
</select>
<select class="classname">
<option value="4">Four</option>
<option value="5" selected>Five</option>
</select>
first uses $()
to construct a jQuery object of the selected options (2, 3 and 5), maps the value attributes into an array of {2,3,5}
and then joins them into a comma-delimited string "2,3,5"
.
cletus
2009-09-22 02:00:27
can you explain what is happening here? whats up with the synatx inside the $()? I will loop up the .map thing on the jquery documentation... what is n and i?
shogun
2009-09-22 02:02:11
woa - that is crazy... I still am having a hard time following one thing: when is the function being passed into .map() actually called? and how many times is it called? Otherwise this is making sense, that is pretty fancy.
shogun
2009-09-22 02:12:01
The function passed into map() is a callback. It is called once per matched element. See http://docs.jquery.com/Traversing/map
cletus
2009-09-22 02:17:32