user1216855
user1216855

Reputation: 275

javascript /jQuery - For Loop

I have a query ajax response which I then use to set the array variables. Is there anyway to use a 'For Loop' to change to #name so that I don't have to write out a line of code to set each array element.

array[0]=$('#event00',response).html();
array[1]=$('#event01',response).html();
array[2]=$('#event02',response).html();
array[3]=$('#event03',response).html();

So '#event00' could be used in a for loop to change to '#event01' etc

Upvotes: 19

Views: 180990

Answers (3)

julioolvr
julioolvr

Reputation: 475

What about something like this?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});

The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

Upvotes: 8

Bot
Bot

Reputation: 11855

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});

Upvotes: 2

Greg
Greg

Reputation: 23463

Use a regular for loop and format the index to be used in the selector.

var array = [];
for (var i = 0; i < 4; i++) {
    var selector = '' + i;
    if (selector.length == 1)
        selector = '0' + selector;
    selector = '#event' + selector;
    array.push($(selector, response).html());
}

Upvotes: 46

Related Questions