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

1.9k views Asked by At

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.

5

There are 5 answers

2
Arun P Johny On BEST ANSWER

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>

0
Balachandran On

Try this:

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

Or

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

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);
});
0
gagan On

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

0
Shreyash Rabadiya On

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

});