Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the attribute id from the element that triggered the event

Tags:

javascript

I have an element, this element calls the function calcTotal via the following code:

$('.pause').change(function(e) {
    window.alert("pause changed");
    calcTotal(e);

The code of calcTotal(e) is as follows:

function calcTotal(event)
{   alert('calcTotal called');
    var myId = event.currentTarget.attr('id');

    myId = myId.replace(/[^0-9]/g, '');

    var timeRegex = /^[0-9]{1,2}:[0-9]{2}$/;

    if($('#start'+myId).val().match(timeRegex) && $('#end'+myId).val().match(timeRegex) && $('#pause'+myId).val().match(timeRegex))
    {
        var minutes = 0;

        var n = $('#end'+myId).val().split(':');
        minutes = parseInt(n[0])*60 + parseInt(n[1]);

        var n = $('#start'+myId).val().split(':');
        minutes -= parseInt(n[0])*60 + parseInt(n[1]);

        var n = $('#pause'+myId).val().split(':');
        minutes -= parseInt(n[0])*60 + parseInt(n[1]);

        var hours = Math.floor(minutes/60);
        minutes = minutes % 60;
        alert(hours + ':' + minutes);
        $('#total' + myId).val(hours + ':' + minutes);
    }
    else
    {       
        $('#total' + myId).val('00:00');
    }

}   

It doesn't work as I had exceptected and when I debug with firebug it says the following:

TypeError: event.currentTarget.attr is not a function
var myId = event.currentTarget.attr('id');  

I would like to store the id of the element in myId. How would I do this?

like image 299
Elian ten Holder Avatar asked Jan 08 '13 20:01

Elian ten Holder


1 Answers

event.currentTarget isn't a jQuery object, so attr is undefined.

You can fix by the following ways:

$(event.currentTarget).attr('id');
event.currentTarget.id;
like image 68
Ricardo Alvaro Lohmann Avatar answered Oct 26 '22 21:10

Ricardo Alvaro Lohmann