How do I use a button to count through an array using JavaScript?

  • A+
Category:Languages

How do I use a button to count through an array using JavaScript?

My code :

var dataset = ["A", "B", "C", "D", "E"]; var counter = 0;  function onClick() {   counter++; };  document.write(dataset[counter]);
<button type="button" onClick="onClick()">Click me</button>

I want to print "A" first, and then "B" when the button is clicked, and so on.

My current code isn't working. How can I fix the code to achieve this?

 


You need a target element for the output, because if the page is finished, you create then a new HTML document.

Please have a look here: Why is document.write considered a "bad practice"?

function onClick() {     if (counter < dataset.length) {         document.getElementById('output').innerHTML += dataset[counter++] + ' ';     } };  var dataset = [ "A" , "B" , "C" , "D" , "E" ],     counter = 0;
<button type="button" onClick="onClick()">Click me</button> <div id="output"></div>

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: