1

I'm using backbone. In my template I have ----

<a href="#" id='<%= member.get("person").id%>'><%= member.get('person').name%></a>

The id is dynamically set. I need to use the id as a variable to make a JSON call.

I've tried a few things -

$('a').click(function(){
        var memberId = $(this).attr("id");
        console.log(memberId);
    })

or

$('a').click(function(){
        var ID = this.attr('id');
        console.log();
    })

and a couple other variations.

Suggestions?

Thanks for all the responses.

I should have mentioned that I was trying these things in the document ready just to see if it would work. My bad, this is my first post on here. Ultimately, the function should be in my view (I think). So it should look more like this -

memberId: function(event){
    $(this).attr('id');
}

Which, again is not working.....

Ari
  • 1,595
  • 12
  • 20

3 Answers3

0
var memberId = $(this).attr("id");

Your first example here should work.

this.id 

should also work.

If you're not seeing output its possible that your id is being set to the empty string. Maybe try prepending some text to test it?

console.log("ID: "+this.id);
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
0

the first version should work, I have a small comment about your code though. Try not using this if you can. Jquery passes the event object as a parameter to the event handler, so you can get a reference to the dom element that triggered this event through something like

$('#test').click(function(el){console.log("here: "+$(el.target).attr('id'))})strong text

user1639848
  • 562
  • 5
  • 15
0

thanks again for your speedy responses.

The following code works -

memberId: function(event){
    memberId = this.model.get('id');
    console.log(memberId);
}

again, I'm using backbone. So the above is a method in a view. below is the necessary piece

this.model.get('id');

i imagine this...

this.get('id');

should work in the document ready.

I'll try to be more clear in the future. thanks again...

Ari
  • 1,595
  • 12
  • 20