1

My idea is when you hover checkbox number 1, the same index number will display the same car from the same position.

var carArray = ["Bmw", "Volvo", "Ferrari", "Audi", "Volkswagen", "Honda"];

So if I hover over the first checkbox it will log "Bmw", if I hover over the fourth, "Audi" will be logged.

var carArray = ["Bmw", "Volvo", "Ferrari", "Audi", "Volkswagen", "Honda"];
var chb = document.querySelectorAll("input[type=checkbox]");

for (var i = 0; i < chb.length; i++) {
  chb[i].addEventListener("mouseover", test);
}

function test() {
  console.log(carArray[i]);
}
body {
  display: flex;
  flex-direction: column;
}
<div><input type="checkbox"> 1</div>
<div><input type="checkbox"> 2</div>
<div><input type="checkbox"> 3</div>
<div><input type="checkbox"> 4</div>
<div><input type="checkbox"> 5</div>
<div><input type="checkbox"> 6</div>
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • well `i` is just whatever it is after the loop is done.... Your code is basically `var i = chb.length; function test(){ console.log(carArray[i]); }` – epascarello Nov 16 '18 at 18:28
  • https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello Nov 16 '18 at 18:30
  • Why not store the the car names in the value of each input. 1 Then just get the .val() of each element as it's hovered over. – Difster Nov 16 '18 at 18:31

2 Answers2

0

You can do something like this:

var carArray = ["Bmw", "Volvo", "Ferrari", "Audi", "Volkswagen", "Honda"];
var chb = document.querySelectorAll("input[type=checkbox]");

chb.forEach((x,i) => x.addEventListener("mouseover", () => test(i)))

const test = i => console.log(carArray[i]);

Issue with your code is that i is by the time passed to your event handler already at 6 value.

var carArray = ["Bmw", "Volvo", "Ferrari", "Audi", "Volkswagen", "Honda"];
var chb = document.querySelectorAll("input[type=checkbox]");

chb.forEach((x,i) => x.addEventListener("mouseover", () => test(i)))

function test(i) {
  console.log(carArray[i]);
}
body {
  display: flex;
  flex-direction: column;
}
<div><input type="checkbox"> 1</div>
<div><input type="checkbox"> 2</div>
<div><input type="checkbox"> 3</div>
<div><input type="checkbox"> 4</div>
<div><input type="checkbox"> 5</div>
<div><input type="checkbox"> 6</div>
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Akrion
  • 18,117
  • 1
  • 34
  • 54
  • instead of referring to `carArray[i]` i would suggest using the `event.target` from the `event` param passed into the event handler method. – Derek Nov 16 '18 at 18:53
0

querySelectorAll() returns a NodeList, there are lot's of ways you can convert it to an array:

Array.from(querySelectorAll('query'));

There's a SO thread showing various ways to handle this:

Fastest way to convert JavaScript NodeList to Array?

Nunchy
  • 948
  • 5
  • 11
  • NodeList implements the iterable protocol, and therefore you can do `for..of` loops easily without converting to an array – Derek Nov 16 '18 at 18:52