Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all,
I have an array and I would like to loop through it with buttons. I have a back and forward button. I wanted to have some kind of index so I can use it as a counter and ++ or -- to pick the index but everytime I try to insert the array[index] into my html it gives me an error.
JavaScript
$(document).ready(function() {
  var arr = [];
  var index = 0;
  var list = "";
  $("#btndis").click(function() {
      $.each(arr, function() {
          list += '<li">'+this.id+' '+this.name</li>';
      });
      $("#section").append(list);
  });
  $("#back").click(function() {
      //var s = arr[index];
      var first = arr.first();
      //$("#sec2").innerHTML(<span>first</span>);
  })
});


What I have tried:

looping array with loops
setting with first()
inserting span and ul li
setting index=0 and doing ++
Posted
Comments
Bohdan Stupak 13-Jan-19 10:13am    
Looks like quotes in your code don't match. Also, it would be nice to know what kind of error do you get
TheBigBearNow 13-Jan-19 16:47pm    
In the button click
$("#back").click(function() {
      //var s = arr[index];
      var first = arr.first();
      //$("#sec2").innerHTML(<span>first</span>);
  })

using var first = arr.first(); to select index[0] in the array and with $("#sec2").innerHTML(first); not being able to display the element on the page
TheBigBearNow 13-Jan-19 17:57pm    
I got it all figured out im not sure why I was having such troubles last night lol probably was just tired and not thinking clearly. It was actually pretty easy when I took time and thought about it.
[code]
$("#back").click(function() {
if (index < 0) {
index = 0;
}
var first = arr[index];
$("#sec2").html('
'+first.id+'
');
index--;
});
[/code]
TheBigBearNow 13-Jan-19 18:47pm    
Now I found an error array index undefined. How can I have it so when i click the btn and its at index 0 it wont go to -1 but i need to be able to click the btn to do index-- to view the next slot in the array.


$("#back").click(function() {
      if (index < 0) {
          index = 0;
      } else {
         var first = arr[index];
         $("#sec2").html('<h5>'+first.id+'</h5>');
         index--;
     }
  });
TheBigBearNow 13-Jan-19 19:07pm    
I know it has something to do with the placement of my "index--"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900