0

I have created javascript function to display array items when index values are entered in input box but it is not working but i want to do it through forloop

<html>
<head>
<title>ForLoop</title>
</head>
<body>
<input id="answer"/><br/><br/>
<button id="btn">Generate</button><br/><br/>
<h1 id="ans"></h1>
<script>
var MyArray=["Lion","Mouse","Cat","Dog","Buffalo","Cow","Rat","Tiger","Monkey","Lepoard","Lizard"]
for(var i=0; i<MyArray.length;i++){
document.getElementById("btn").onclick=function(){
if( document.getElementById("answer").value==MyArray[i]){
document.getElementById("ans").innerHTML=MyArray[i]
}
}


}

</script>
</body>
</html>

3 Answers 3

3

There are couple of issues.

  1. You are attaching the event listener inside for-loop. Infact there is no need of for -loop;

  2. You need to do same document.getElementById('ans') .innerHTML to update ans DOM element.

Hope this snippet and demo will be useful

var MyArray=["Lion","Mouse","Cat","Dog","Buffalo","Cow","Rat","Tiger","Monkey","Lepoard","Lizard"]
document.getElementById("btn").onclick=function(){
var _ip =document.getElementById("answer").value;
document.getElementById("display").innerHTML=MyArray[_ip];
}

JSFIDDLE

Sign up to request clarification or add additional context in comments.

Comments

2

Use value as index of array

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

The Node.textContent property represents(gets/sets) the text content of a node and its descendants.

Consider following scenarios as well:

  • If value is empty('')
  • If provided index does exist in array

var MyArray = ["Lion", "Mouse", "Cat", "Dog", "Buffalo", "Cow", "Rat", "Tiger", "Monkey", "Lepoard", "Lizard"];
document.getElementById("btn").onclick = function() {
  var ans = document.getElementById('answer').value;
  document.getElementById("ans").textContent = (ans === '') ? '' : MyArray[+ans] || '';
}
<input id="answer" />
<br/>
<br/>
<button id="btn">Generate</button>
<br/>
<br/>
<h1 id="ans"></h1>

Comments

0
<html>
<head>
<title>ForLoop</title>
</head>
<body>
<input id="answer"/><br/><br/>
<button id="btn">Generate</button><br/><br/>
<h1 id="ans"></h1>
<script>
  var MyArray=["Lion","Mouse","Cat","Dog","Buffalo","Cow","Rat","Tiger","Monkey","Lepoard","Lizard"];
  document.getElementById("btn").onclick=function(){
    var index = parseInt( document.getElementById("answer").value ) || 0;
    var ans=MyArray[ index ];
    document.getElementById("display").innerHTML= ans;
  }//onclick
</script>
</body>
</html>

3 Comments

Please check now, I had copied your code and it had some extra braces.
@ Mohit Bhardwaj still not i do not want to display as alert but as a text
@MandarSant updated my code to display as text in #display element.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.