Dean Byron
Dean Byron

Reputation: 31

Javascript for loop function array

I'm bit of a javascript newbie - I'm trying to make a function that when I click a button it will call out a single object out of my array, in order.

Upvotes: 1

Views: 695

Answers (5)

Math
Math

Reputation: 1

<script type="text/javascript">

    var myArray = ["aa","bb","cc","dd","ee"],
        num=0;
    function call() {  
        document.getElementById("placeDiv").innerHTML = myArray[num];
        num++;
    };
</script>

<button onclick="call()">Click!</button>
<div id = "placeDiv"></div>

Upvotes: -2

PSL
PSL

Reputation: 123739

Try this:- You are looping through on each click and assigning value to the element innerHTML so it will always have only the last value from the array.

Demo

var myArray = ["aa","bb","cc","dd","ee"];
var i = 0;
function call(){
     if(myArray.length <= i) i=0;

       document.getElementById("placeDiv").innerHTML = myArray[i++];
}

if you don't want to use a global variable you can use this way too.

http://jsfiddle.net/zZ4Rm/

Use shift method on array to get the first item and then push it back tht end of the array for the cycle to happen.

var myArray = ["aa","bb","cc","dd","ee"];

function call(){
    var val = myArray.shift();
    myArray.push(val);
    document.getElementById("placeDiv").innerHTML = val;
}

Upvotes: 1

Eric Jablow
Eric Jablow

Reputation: 7889

You want a closure.

var call = (function() {
    var i = 0,
    entries = ["aa", "bb", "cc", "dd", "ee"];
    return function() {
        return entries[i++ % entries.length];
    };
})();

This keeps i and entries as private values, and returns a function that goes to the next entry in the list each time it is called.

Upvotes: 1

ckpepper02
ckpepper02

Reputation: 3437

You are overwritting your placeDiv with innerHTML.

Try using:

function call(){
  var yourVar= document.getElementById('placeDiv'); 
    for (var i=0; i < myArray.length; i++) {
           yourVar.innerHTML = yourVar.innerHTML + myArray[i];
 }
}

Upvotes: 0

Bergi
Bergi

Reputation: 664297

all it does is display "ee".

Of course, you are looping through the whole array and assigning each item to the innerHTML of that one element - and only the last one will stay there and show up.

What I want it to do is when I click the button to display "aa" then when I press it again to display "bb" instead of "aa" and so on.

Then you can't use a for-loop, but have to keep track of the counter manually and execute only one step per invocation of call.

var myArray = ["aa","bb","cc","dd","ee"];
var i=0;
function call() { 
    document.getElementById("placeDiv").innerHTML = myArray[i];
    if (i < myArray.length-1)
        i++;
    else
        i = 0; // restart, but you may as well show an error message
}

Upvotes: 1

Related Questions