denormalizer
denormalizer

Reputation: 2214

How to get the id of an element on a button click in mootools(1.1)

I have a bunch of links with non-pre-determined id's like so:

<a href="#" class="remove_pid" id="pid_123">Remove 123</a>
<a href="#" class="remove_pid" id="pid_234">Remove 234</a>
<a href="#" class="remove_pid" id="pid_567">Remove 567</a>
<a href="#" class="remove_pid" id="pid_890">Remove 890</a>

I have an event handler like so:

$$('.remove_pid').addEvents({
   'click': removePid
});

which calls this function

function removePid(event)
{
    alert('yo what is my element id???');
}

So the question is how do i get the element id in the function removePid()?

UPDATE:

@Aishwar, event.target.id seems to work in the following case, but not specifically in my case

<a href="#" class="remove_pid"><img src="/123.jpg" id="pid_123"></a>

UPDATE 2:

I thought it was inconsequential, but instead of the text "Remove 123" I actually have an image like so:

<a href="#" class="remove_pid" id="pid_123"><img src="/123.jpg"></a>

So, thanks for @Dimitra for pointing it out. I was surprised with the de-vote but am happy to say i probably deserve it.

Upvotes: 1

Views: 929

Answers (3)

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

as per the markup posted in the FINAL update:

http://www.jsfiddle.net/dimitar/Sr8LC/

$$('.remove_pid').addEvents({
    'click': function(e) {
        new Event(e).stop();
        var id = this.getProperty("id");
        alert(id);
        alert(id.replace("pid_", ""));
    }
});

to use a named function and keep the event:

var removeProduct = function(e) {
    new Event(e).stop();
    var id = this.getProperty("id");
    alert(id);
    alert(id.replace("pid_", ""));
};

$$('a.remove_pid').each(function(el) {
    el.addEvents({
        'click': removeProduct.bind(el)
    });
});

within both functions, this will refer to the trigger element (the anchor), so you can read it's property, etc. this.getFirst() will reference the image (if you want it).

Upvotes: 1

denormalizer
denormalizer

Reputation: 2214

Think I found it:

function removePid(event)
{
    //alert('yo what is my element id???');
    $(event.target).getParent('a').getProperty('id');
}

This works in FF 3.6

Upvotes: 0

Aishwar
Aishwar

Reputation: 9714

I do not have experience working with mootools. But I would guess you can just do something along these lines, in removePid:

var element = event.srcElement || event.target
element.id // is the element's id, element is the DOM element itself

Upvotes: 1

Related Questions