Snote
Snote

Reputation: 955

Get multiple elements by a list of id's with jQuery

I have that in my html

<input type="checkbox" id="1234">
<input type="checkbox" id="2345">
<input type="checkbox" id="3456">
<input type="checkbox" id="4567">
<input type="checkbox" id="5678">

And an list of id 1234 2345 3456 or #1234 #2345 #3456

I want to get all the element of the list whose id is in the list of id

I try $(":checkbox").attr('id', items_id); and var items_cb = $(":checkbox[id='items_id']"); where items_id is the list of item, but it doesn't work.

Upvotes: 10

Views: 16276

Answers (7)

kommradHomer
kommradHomer

Reputation: 4210

you can just build a selector string like :

var selectorString = '';
for id in idList:
    selectorString = '#' + idList[id] + ',';

then you can use the selectorString as :

 $(selectorString)

to select them.

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87083

var arr = ['1234', '2345', '3456'];
var elem = [];
$('body > input').filter(function() {
    if ($.inArray(this.id, arr) != -1) {
        elem.push({
            id: this.id,
            type: $(this).prop('type'),
            name: this.nodeName
        });
    }
});
console.log(elem);
console.log(elem.length);

Upvotes: 1

Piotr Kula
Piotr Kula

Reputation: 9841

You can use the jQuery each method that will loop through all the selected elements.

HTML

<input name="myradio" type="checkbox" id="colour1">
<input name="myradio "type="checkbox" id="colour2">
<input name="myradio" type="checkbox" id="colour3">

JavaScript

$('input:radio[name=myradio]').each(function (index) {
        alert(index + ': ' + $(this).val()); //is it checked?
        alert(index + ': ' + $(this).attr('id')); //ID string
        //You can compare if is this ID in items_id in this loop
});

Upvotes: 1

M S
M S

Reputation: 4093

Try this

$('#1234, #2345, #3456')

Upvotes: 3

Thomas Kelley
Thomas Kelley

Reputation: 10302

$("#1234, #2345, #3456")

...should work.

http://api.jquery.com/multiple-selector/

Upvotes: 0

wong2
wong2

Reputation: 35750

var result = [];
for(var i=0; i < items_id.length; i++){  
    var id = items_id[i];
    result.push($(id))  
}
// result is what you want

Upvotes: 0

Samich
Samich

Reputation: 30165

Just try to put all id's in selector separated by comma:

$('#1234, #2345, #3456')...

Code: http://jsfiddle.net/3df6W/

P.S. ID's shouldn't start with digits.

Upvotes: 14

Related Questions