3

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?

Ryan Walls
  • 61
  • 1
  • 8
破嘎獸
  • 35
  • 3

7 Answers7

5

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>
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
3

You should write it inside onClick() function. So that whenever the user clicks the button, onClick() function gets invoked and changes the value in the element using innerHTML property.

It's best practice to create a element separately and change its value instead of using document.write.

var dataset = ["A", "B", "C", "D", "E"];
var counter = 0;

function onClick() {
  
    const para = document.getElementById('para');
    para.innerHTML = dataset[counter];
    if(counter < (dataset.length-1)) {
      counter++;
    } else {
      counter = 0; 
    }

};
<button type="button" onClick="onClick()">Click me</button>
<p id="para"></p>
Bear Nithi
  • 3,961
  • 13
  • 28
1

Your script at the bottom will only run once when the page loads, so it doesn't have any idea that counter is changing. Instead, you can add the document write to your onClick method.

Also, at the moment you are appending your letter to the body, replacing everything that was there before, including the button. Instead, you can create a div which will hold the resulting letter pulled from your array.

Moreover, I suggest you use counter % dataset.length so that your letter wraps around each time you reach the end of your array:

<script type="text/javascript">
  var dataset = ["A", "B", "C", "D", "E"];
  var counter = 0;

  function onClick() {
    document.getElementById("res").textContent = (dataset[counter % dataset.length]);
    counter++;
  };
</script>

<button type="button" onClick="onClick()">Click me</button>

<div id="res"></div>
Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
1

This will help you

  var dataset = ["A", "B", "C", "D", "E"];
  var counter = 0;

  function onClick() {
    document.getElementById("in").innerHTML = dataset[counter];
    counter++;
    if(counter == dataset.length) counter = 0;
  };
<button type="button" onClick="onClick()">Click me</button>
<p id ="in"></p>
Syed Mehtab Hassan
  • 1,196
  • 1
  • 7
  • 21
0

You can have a div and target it onClick and add value from dataset to it using innerHTML

<script type="text/javascript">
var dataset = [ "A" , "B" , "C" , "D" , "E" ];
var counter = 0;
function onClick() {
document.getElementById('data').innerHTML = dataset[counter]
  counter++;
  counter = counter % 5
};

</script>

<button type="button" onClick="onClick()">Click me</button>
<div id='data'></div>
Code Maniac
  • 33,907
  • 4
  • 28
  • 50
0

var dataset = ["A", "B", "C", "D", "E"];
var counter = 0;

function onClick() {
/* If you want the previous result to be removed and new result to appear use the below code*/
/*document.getElementById("result").innerHTML =dataset[counter]; */
/* Or if you want to append the result, retaining the previous result use this  */
document.getElementById("result").innerHTML+=(dataset[counter] + ", ");
   
  counter++;
  if(counter == 5){
    counter = 0;
  }
};
<button type="button" onClick="onClick()">Click me</button>
<div id='result'></div>
Kumar Aman
  • 271
  • 2
  • 7
0

The code executed on click is:

function onClick() {
  counter++;
}

As you can see, the counter is incremented but the screen is not refreshed. To fix this problem you could think of copying document.write(counter) inside the function, but the first time the button is clicked document.write overwrites the original HTML and the button disappears:

counter = 0;
document.write(counter);

function onClick() {
  counter++;
  document.write(counter);
}
<button onclick="onClick()">increase</button>

To refresh the screen properly you need to know what the DOM is. Roughly speaking, the DOM (Document Object Model) is an equivalent of your HTML document in the JavaScript world. Thanks to the DOM you can manipulate the HTML document using JavaScript.

Think of an HTML document as a tree with parent and child elements (for example <html> has two children, <head> and <body>). The root of this tree is the document itself, and the first child of the document is the <html> element. In the JavaScript world, the document can be found in a preexisting variable called document. You can ask document to find some descendant elements for you like so:

html = document.children[0];
buttons = document.getElementsByTagName("button");

You can also manipulate the elements one by one. For example, if you want to change the text inside the button, you can do it like so:

button = buttons[0]; // first button found in the tree
button.textContent = "counter plus plus";

Based on this knowledge, here is a possible solution to print the counter on click:

counter = 0;

function onClick() {
  counter++;
  var span = document.getElementById("counter");
  span.textContent = counter;
}
<button onclick="onClick()">increment</button>
<span id="counter">0</span>

I suppose you can finish the job by yourself :-)

leaf
  • 14,210
  • 8
  • 49
  • 79