0

 var show=[
 "p1",
 "p2",
 "p3"
 ];
 var n;
 function show(n){
 for(n=1;n<=3;++n){
 
 
 document.getElementById("show").innerHTML=show[n];
 }
 }
<button onclick="show(1)">b1</button>
 <button onclick="show(2)">b2</button>
 <button onclick="show(3)">b3</button>
 
 <p id="show"></p>

I am trying to print p1,p2,p3 when I click b1,b2,b3 respectively. How can I do it.

cccn
9491 gold badge8 silver badges20 bronze badges
asked Apr 13, 2020 at 10:46
1
  • Rename the array, it overrides the function with the same name. Also, arrays have zero-based indexing. Commented Apr 13, 2020 at 10:49

2 Answers 2

1

Your code has several problems.

First, do not name your variable and the function with the same name. In this example, you can rename the array as showArr.

Then you need to remove for loop (it is against what you are trying to achieve). And you need to pass index - 1 when getting the array item with index.

And there is no need for a variable n in the global scope (it is redundant).

var showArr = [
 "p1",
 "p2",
 "p3"
];
function show(n) {
 document.getElementById("show").innerHTML = showArr[n - 1];
}
<button onclick="show(1)">b1</button>
<button onclick="show(2)">b2</button>
<button onclick="show(3)">b3</button>
<p id="show"></p>

answered Apr 13, 2020 at 10:50
Sign up to request clarification or add additional context in comments.

Comments

0

Just don't use the same name show for the variable and the function:

var show = [
 "p1",
 "p2",
 "p3"
];
function showIt(n) {
 document.getElementById("show").innerHTML = show[n - 1];
}
<button onclick="showIt(1)">b1</button>
<button onclick="showIt(2)">b2</button>
<button onclick="showIt(3)">b3</button>
<p id="show"></p>

answered Apr 13, 2020 at 10:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.