1

I have an array called selected as follows :

var selected = [];

example value of selected from console would return :

["97", "98", "99", "101", "103", "105", "106"]

I need to turn these into a multiple selector of ids... for example :

$('#97', '#98', '#99', '#101', '#103', '#105', '#106').click( function () {
    alert('hi');
});

2 Answers 2

1

Simple solution: use join.

Example:

http://jsbin.com/qihep/1/edit?js,output

var selected = 
    ["97", "98", "99", "101", "103", "105", "106"];

var selector = "#" + selected.join(", #");

Browser compatibility is perfect, as per:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join#Browser_compatibility

Sign up to request clarification or add additional context in comments.

Comments

0

Fiddle Demo

$('#' + ["97", "98", "99", "101", "103", "105", "106"].join(',#')).click(function(){
  //code here
});

arr.join(separator)


'#' + ["97", "98", "99", "101", "103", "105", "106"].join(',#')

# for the first element than all other elements are joined by .join(',#') i.e ,#


In case of variable use it like this

'#' + selected.join(',#')

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.