3

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!

Vindberg
  • 1,502
  • 2
  • 15
  • 27

3 Answers3

11

You could change the second line like this:

var selectedIdsStr = selectedIdsArray.get().join(',');
marcob
  • 1,003
  • 2
  • 11
  • 23
  • Hi, thanks for your reply. The generated jquery array cannot be joined using the normal js function. At least its not working for me. – Vindberg Jul 23 '09 at 14:44
  • var selectedIdsStr = selectedIdsArray.get().join(','); I forgot .get() ..sorry – marcob Jul 23 '09 at 14:57
3
var selectedIdsStr = $("#selectId option:selected").map(function(){
   return $(this).val();
}).get().join(",");

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

DLH
  • 2,771
  • 3
  • 23
  • 30
0

You can also change the second line to this:

var selectedIdsStr = selectedIdsArray.get().toString()
Diego Carrion
  • 513
  • 5
  • 8