0

It's a small piece of code, but I can't get it to work. I have a menu which is filled dynamically with javascript, and I add an eventlistener on click for every button. Now every button needs a different function, so I loop through them

var list = $("a");
for (var i=0; i<list.length; i++) {
    $(list[i]).on("click",function(){alert(i);});
}

With this code every button will give me an alert with 5, instead of 1,2,3,... How do I fix this?

  • 2
    use a closure: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – A. Wolff Mar 12 '14 at 19:17

3 Answers3

1

Use each() that's what it's for:

var list = $("a");
list.each(function(index){
    $(this).on("click", function(){alert(index);});
});

DEMO

Wilmer
  • 2,511
  • 1
  • 14
  • 8
0

The value of i changes in the loop, but after the loop is finished the value of i is 5. Whenever you call the alert, it is looking for the variable i, whose value is now 5. You need to store the increment value of i somewhere for each thing. In this example, I give each button an HTML5 data attribute called data-myvalue.

for (var i=0;i<ins.length;i++){
    ins[i].setAttribute('data-myvalue',i);
    ins[i].addEventListener('click',
           function(){alert(this.getAttribute('data-myvalue'));});
}

jsfiddle

But you can also store the information in javascript array.

Ryan Kohn
  • 13,079
  • 14
  • 56
  • 81
user2782001
  • 3,380
  • 3
  • 22
  • 41
0

in your html code call a function favbrowser whenever a item is selected using onchange event by writting

<select id="myList" onchange="favBrowser()">
  <option></option>
</select>

and then in javascript do this to print the name of menu item

<script>
function favBrowser()
{
var mylist=document.getElementById("myList");
alert(mylist.options[mylist.selectedIndex].text);
}
</script>
Arjun Chaudhary
  • 2,373
  • 2
  • 19
  • 36