0

I made 5 buttons, an array object which has countries names, and an empty paragraph.

I want the innerHTML of the paragraph to display the corresondent name based on index of a for loop I implemented, such a way that if I click the first button the paragraph display the first country in the array and so on. But I this error in console:

Cannot read property 'country' of undefined

this is the html:

<p id="par"></p>
<button class="but" id="1">1</button>
<button class="but" id="2">2</button>
<button class="but" id="3">3</button>
<button class="but" id="4">4</button>
<button class="but" id="5">5</button>

and this is the js:

var bArr = $(".but")
var paises = [
  {country: "India", growth: 35},
  {country: "Indonesia",growth: 30},
  {country: "Russia",growth: 25},
  {country: "Mars",growth: 20},
  {country: "Pluton",growth: 15}    
]

for (i = 0; i< bArr.length; i++){
  $(bArr[i]).click(function(){
    $("#par").html(paises[i].country)
  })
}

Please, can anyone help me figure out what's the problem?

Thanks

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Julio Rodriguez
  • 499
  • 6
  • 16

1 Answers1

3

You don't need to use a for loop. Add a click event listener to all buttons and in the event handler get the id attribute of the clicked button and use that to select the relevant item of array.

var paises = [
  {country: "India", growth: 35},
  {country: "Indonesia",growth: 30},
  {country: "Russia",growth: 25},
  {country: "Mars",growth: 20},
  {country: "Pluton",growth: 15}
];
$(".but").click(function(){
  $("#par").text(paises[this.id-1].country);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="par"></p>
<button class="but" id="1">1</button>
<button class="but" id="2">2</button>
<button class="but" id="3">3</button>
<button class="but" id="4">4</button>
<button class="but" id="5">5</button>
Mark
  • 90,562
  • 7
  • 108
  • 148
Mohammad
  • 21,175
  • 15
  • 55
  • 84