Mohan Ram
Mohan Ram

Reputation: 8463

How to pass id dynamically in jquery

I had array of div id i need to close all that div. i had used code below. not works. how to do this.

$.each([id_1, id_2], function(index, value) { 
  //alert(index + ': ' + value); 

$("#"+value).css({'display' : 'none'});

});

i need to pass id dynamically as $("#"+id_value)

Upvotes: 2

Views: 4989

Answers (3)

karim79
karim79

Reputation: 342635

Try passing them as strings? i.e.:

$.each(['id_1', 'id_2'], ...

You can also programattically build up a Multiple Selector as others have suggested, but if you don't like the idea of having a 10,000 character long selector, and if your IDs already follow a naming convention (such as 'myid_1', 'myid_2', 'myid_10', etc.) then I would suggest using the startsWith selector, like this:

$("[id^=myid]").hide(); // hide all elements with ID starting with 'myid'

Upvotes: 1

Matt
Matt

Reputation: 75307

You can use the Array join method as follows:

var idsInJquerySyntax = '#' + [id_1, id_2, id_3].join(', #');

$(idsInJquerySyntax).css({
 display: 'none'
});

You can see a working demo here: http://www.jsfiddle.net/qHVg7/

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630379

You could just turn it into a multiple selector via .join(), like this:

$('#'+[id_1, id_2].join(',#')).hide();

This would basically be doing:

$('#someId1,#someId2').css({'display' : 'none'});

.hide() sets display: none, but in a way that .show() will restore it to the previous value.

Upvotes: 0

Related Questions