0

How can I pass the id to the function in the following javascript code?

for(var i = 1; i<=10; i++){     
    var id = i;
        $("#result-" + id).click(function(event){
        makeFeatureSelected(id, true);
    });
}

In this way, the value of id is always 11.

Thanks.

er_benji
  • 305
  • 4
  • 9
  • see more about [closure](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1) – Grundy Feb 14 '14 at 15:06

4 Answers4

1

An elegant solution could be:

var makeFeatureSelected = function(id, val) {
  console.log(id);
}

$('[id^="result-"]').on('click', function() { 
    var id = $(this).attr('id').split('-')[1];
    makeFeatureSelected(id, true);
});

Explanation

  • $('[id^="result-"]') JQuery's selector: select all element that have an id that starts with string "result-"
  • $(this).attr('id').split('-')[1]: split id string of element clicked and take the second value, in your case the id;

Plus
If you want to do something only with 10 first id, you can add an if block to check id.

Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
0

I think it'd just be as easy as passing ID as a parameter to your function.

for(var i = 1; i<=10; i++){     
    var id = i;
        $("#result-" + id).click(function(event, id){
        makeFeatureSelected(id, true);
    });
}
snollygolly
  • 1,858
  • 2
  • 17
  • 31
0

why don't you just extract it from the ID?

for(var i = 1; i<=10; i++){     

        $("#result-" + id).click(function(event){
        var id = $(this).attr('id').match(/\d+/)[0];
        makeFeatureSelected(id, true);
    });
}

that way you could skip the for loop and just assign a class to all result elements. A little tidier perhaps?

Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
0

In your code snippet id is always 11 because of the closure formed when you define a function within a loop. This is a common mistake in javascript.

The way around this is by making further use of closures.

function makeSelectedCallback(id){
    return function(){
        makeFeatureSelected(id, true);
    }
}

function yourExistingLoopLogic(){
    for(var i = 1; i<=10; i++){     
        var id = i;
        $("#result-" + id).click(function(event){
            makeSelectedCallback(id, true);
        });
    }
}

Have a read of the Mozilla closure guide it covers closures in detail

Jaimie Whiteside
  • 1,180
  • 9
  • 21