Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing 'this' as parameter in JavaScript

I have the following code:

HTML:

<label id="copyAddress" class="copyAddress" onclick="CopyAddress(this);">
    Copy Address
</label>

JS:

function CopyAddress(copyAddressLink) {    
  PopulateTarget(copyAddressLink);   
}

function PopulateTarget(link) {
  var targetGroup = $(link).closest('someClass');    
}

In PopulateTarget function 'link' variable is undefined, while in CopyAddress it has values as is should.

What can cause this problem? Is there some restriction for passing parameters in Java Script? How this should behave? If you need more code to post please tell me.

like image 547
eomeroff Avatar asked Feb 21 '23 15:02

eomeroff


2 Answers

Since you are anyhow using jQuery, why are you using obtrusive Javascript?

Use this instead:

HTML:

<label id="copyAddress" class="copyAddress">Copy Address</label>

Javascript:

$(document).ready(function(){
    $('#copyAddress').click(function(){
        var targetGroup = $(this).closest('.someClass');    
    });
});
like image 172
Joseph Silber Avatar answered Mar 01 '23 01:03

Joseph Silber


You're missing a dot on "someClass", it should be ".someClass".

Maybe your code will work after you fix that. However: since you're using jQuery (it seems you are), you should attach the click handler the jQuery way, instead of inline on the HTML. This means:

$(document).ready(function(){
    $('#copyAddress').click(CopyAddress);
})

function CopyAddress() {    
    PopulateTarget(this);   
}

function PopulateTarget(link) {
    var targetGroup = $(link).closest('someClass');    
}
like image 28
bfavaretto Avatar answered Mar 01 '23 00:03

bfavaretto