views:

2829

answers:

2

Hi all, using jQuery I have the following code:

var selectedIdsArray = $("#selectId option:selected").map(function(){return this.value;});
var selectedIdsStr = $.map(selectedIdsArray, function(val){ return "" + val + "";});

It successfully retrieves a string of ids eg. selectedIdsStr = "2,45,245,1" from an <select multiple='multiple'> element. I was wondering if there is a more efficient way (less code) to achieve this?

Thanks!

+1  A: 

You could change the second line like this:

var selectedIdsStr = selectedIdsArray.get().join(',');
crossy
Hi, thanks for your reply. The generated jquery array cannot be joined using the normal js function. At least its not working for me.
Anders Vindberg
var selectedIdsStr = selectedIdsArray.get().join(',');I forgot .get() ..sorry
crossy
No worries, thanks for the help guys!
Anders Vindberg
+1  A: 
var selectedIdsStr = $("#selectId option:selected").map(function(){
   return $(this).val();
}).get().join(",");

adapted from http://docs.jquery.com/Traversing/map#callback

DLH