javascript /jQuery - For Loop

177,232

Solution 1

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());
}

Solution 2

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".

Solution 3

.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();
});
Share:
177,232
user1216855
Author by

user1216855

Updated on July 05, 2022

Comments

  • user1216855
    user1216855 almost 2 years

    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

  • Bot
    Bot about 12 years
    @MДΓΓБДLL roger, i will add that.
  • nnnnnn
    nnnnnn about 12 years
    How does this relate to the code in the question, which is setting array values? Calling .html() on a line by itself doesn't do anything...
  • Bot
    Bot about 12 years
    @nnnnnn good catch, I forgot to add it to the array. I have removed it and replaced it with map.
  • Ed DeGagne
    Ed DeGagne over 11 years
    Completely agree Greg!! Native functions are always faster than any helper counterparts.