1

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.

Dean Byron
  • 31
  • 6

5 Answers5

1

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
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

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;
}
Community
  • 1
  • 1
PSL
  • 123,204
  • 21
  • 253
  • 243
1

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.

Eric Jablow
  • 7,874
  • 2
  • 22
  • 29
0

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];
 }
}
ckpepper02
  • 3,297
  • 5
  • 29
  • 43
-2
<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>
flavian
  • 28,161
  • 11
  • 65
  • 105
Math
  • 1