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!

3 Answers 3

11

You could change the second line like this:

var selectedIdsStr = selectedIdsArray.get().join(',');
Sign up to request clarification or add additional context in comments.

2 Comments

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

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

Comments

0

You can also change the second line to this:

var selectedIdsStr = selectedIdsArray.get().toString()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.