mare
mare

Reputation: 13083

$(this) and event.target different but should be the same

I have the following code that wires up the click event function to the submit button. I am aware that event.target and this are not always the same (as I understand it depends where the event was attached to and who actually fired it) but in this case the event was attached to the button and the button also fired it, so they should be the same. Or am I wrong?

 modals.init = function () {
    // wire up submit() function to the submit button
    modals.config.$submitBtn.on('click', submit);
  };

  function submit(event) {
    event.preventDefault();
    var $this = $(this);
    alert(event.target.id); // fine
    alert($this.id); // undefined
}

Upvotes: 1

Views: 111

Answers (4)

Mic
Mic

Reputation: 523

With the code $(this) you generate a jquery object and you have to use the jquery functions: alert($this.attr("id));.

Upvotes: 1

Bergi
Bergi

Reputation: 664599

Yes, then this === event.target.

But if you wrap it into a jQuery wrapper, it has no id property any more. You can either use this.id or $(this).attr('id') to get the attribute or $(this).prop('id') to get this.id.

Upvotes: 2

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

It is $this.attr("id") (jQuery element) or this.id (DOM element)

Upvotes: 5

Vithozor
Vithozor

Reputation: 620

In this case, the this is bounded to be the element clicked, so there is no .id property, it's the jQuery representation of the element clicked.

Upvotes: 1

Related Questions