19

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

2
  • 1
    drop the extra Zero '0'. It will help you a lot, trust.. and I'd leave out the 00 and 0 count all together. Commented Feb 29, 2012 at 20:51
  • What ended up working for you? Commented Mar 1, 2012 at 18:23

3 Answers 3

46

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());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Completely agree Greg!! Native functions are always faster than any helper counterparts.
8

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

Comments

2

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

3 Comments

@MДΓΓБДLL roger, i will add that.
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...
@nnnnnn good catch, I forgot to add it to the array. I have removed it and replaced it with map.

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.