David Panart
David Panart

Reputation: 656

Javascript target attribute undefined

I'm having an issue with my code :

I build a notification from accepting a friend request. I can then choose between three actions (accept, refuse or block).

HTML

<div class="pull-right">
    <a href="#" title="{{_ "notifications.accept"}}" id="ok-btn" name=" {{data.talkmateId}}">
        <span class="glyphicon glyphicon-ok-circle" id="ok-sign" aria-hidden="true"> </span>
    </a>
    <a href="#" title="{{_ "notifications.remove"}}" id="remove-btn" name="{{data.talkmateId}}">
        <span class="glyphicon glyphicon-remove-circle" id="remove-sign" aria-hidden="true"> </span>
    </a>
    <a href="#" title="{{_ "notifications.block"}}" id="block-btn" name="{{data.talkmateId}}">
      <span class="glyphicon glyphicon-remove-sign" id="block-sign" name="{{data.talkmateId}}" aria-hidden="true"> </span>
    </a>
  </div>

Meteor.Js

Template.navigation.events({
'click #block-btn': function(e, tmpl){
      var friendList = Meteor.user().profile.friends;
      var usrId = e.target.id;
      var i = 0;
      console.log(e.target.id);
      console.log(friendList);
      /*for(i = 0; i < friendList.length; i++){
        if(friendList[i].id == usrId){
          console.log(i);
          friendList.splice(i, 1);
          break;
        }
      }
      console.log(friendList);
      Meteor.users.update({_id: Meteor.userId()}, {
        $set: {
          'profile.friends': friendList
      }});
      Meteor.users.update({_id: Meteor.userId()}, {
        $push: {
          'profile.blocked': usrId
        }
      });*/
      //Meteor.call('removeNotif', Meteor.user()._id, this.id);
    }
  });

The problem is that no matter what I tried, I never get what I want. The goal is that when I accept or block or remove some one, I change the friend status, and / or delete it from my profile and / or add it to the blocked list.

But each time, I can't as the e.target.id printed is the one of the span and not the one of the <a></a>. I tried to pass the user ID in the name attribute, but it doesn't work, and the log print only "undefined".

I tried to get it from the data- attribute too, but I got an issue for each way I accessed it (JQuery .data(), HTML5 .dataset or vanilla JS .getAttribute("data-").

Spent my night on this, couldn't find a real solution. Could someone guide me ?

Thanks you

Upvotes: 0

Views: 921

Answers (1)

Carson Moore
Carson Moore

Reputation: 1287

You can turn the event.target object into a jQuery object and then use selectors on it to get its parent using jQuery.parent(), like so:

var $target = $(event.currentTarget);
var $parent = $target.parent(); // gets you the `a` tag as a jQuery object
var parentId = $parent.attr('id');
var parentTalkmate = $parent.attr('name')

You can play around with that with this simple fiddle.

Upvotes: 2

Related Questions