Krzysztof Płaneta
Krzysztof Płaneta

Reputation: 13

jquery $(this).attr('href') returns undefined

I've got a very simple code

HTML

<a class="qqPopupCTA" href="http://example.com">Button</a>

JS

$qqPopupCTA = $('.qqPopupCTA');

function showForm(e){

    e.preventDefault();

    var targetPageUrl = $(this).attr('href');

    // do stuff
}

$qqPopupCTA.on('click', function(e){showForm(e);});

However I keep getting undefined href. Console.log($(this)) returns "window" and console.dir($(this)) returns "e.fn.init[1]"

Any idea what am I doing wrong? The code is super simple so I must be missing something obvious.

I think I've tried everything.

Upvotes: 1

Views: 1998

Answers (5)

Shreyash Rabadiya
Shreyash Rabadiya

Reputation: 131

$('.qqPopupCTA').on('click', function showForm() { var targetPageUrl = $(this).attr('href'); alert(targetPageUrl)

});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

When you call showForm(e), the context(this) is not the anchor object inside showForm it is the window object.

So you can just pass the function reference as the click handler

$qqPopupCTA.on('click', showForm);

$qqPopupCTA = $('.qqPopupCTA');

function showForm(e) {
  e.preventDefault();
  var targetPageUrl = $(this).attr('href');
  alert(targetPageUrl)

  // do stuff
}

$qqPopupCTA.on('click', showForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="qqPopupCTA" href="http://example.com">Button</a>

or pass a custom context to the showForm function using .call()

$qqPopupCTA.on('click', function (e) {
    showForm.call(this, e);
});

$qqPopupCTA = $('.qqPopupCTA');

function showForm(e) {
  e.preventDefault();
  var targetPageUrl = $(this).attr('href');
  alert(targetPageUrl)

  // do stuff
}

$qqPopupCTA.on('click', function(e) {
  showForm.call(this, e)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="qqPopupCTA" href="http://example.com">Button</a>

Upvotes: 1

gagan
gagan

Reputation: 21

The function showForm is defined globally , 'this' refers to window object . showForm(e,this) will give the reference of current element to the function.so passing the 'this' should fix your undefined this

Upvotes: 0

Satpal
Satpal

Reputation: 133403

As per your approach this in the function setCurrent doesn't refers to the element which invoked the event. it is window object

Just pass function reference to when binding event

$qqPopupCTA.on('click', showForm);

OR, You can use bind()

$qqPopupCTA.on('click', function (e) {
    showForm.bind(this)(e);
});

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

Try this:

$qqPopupCTA.on('click', showForm); // pass function name(ref) 

Or

$qqPopupCTA.on('click', function(e){
      showForm.call(this,e);
});

Upvotes: 0

Related Questions