Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the reference 'this' to a javascript function from an <a> tag

I know that this is elementary, but I'm completely unable to pass "this" as a parameter to a JavaScript function. I'm numb from trying...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
    function ko(control.id){
    alert(control);
}
</script>

<body>
<div id"lala">
    <a id="la" href="javascript:ko(this)" >Votes & Concerns</a>
</div>

</body>
</html>

The alert tells me "undefined!"

like image 364
DKean Avatar asked Jan 26 '12 22:01

DKean


People also ask

How do you call a function from a tag in JavaScript?

Step 1: Firstly, we have to type the script tag between the starting and closing of <head> tag just after the title tag. And then, type the JavaScript function. Step 2: After then, we have to call the javaScript function in the Html code for displaying the information or data on the web page.

How do you pass HTML tags in JavaScript?

Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.

How do you pass this function in HTML?

Use the onclick attribute in a button tag with the function name and pass value in this function. With this method, you can also take input from users and pass parameters in the JavaScript function from HTML.


2 Answers

<a id="la" href="#" onclick="ko(this); return false;" >Votes & Concerns</a>
like image 187
ori Avatar answered Oct 06 '22 01:10

ori


Don't do it from the "href" value, do it from a real event handler attribute:

<a id='la' href='#' onclick='ko(event, this)'>

Pass in the event so that you can prevent the default interpretation of a click on an <a> from being undertaken by the browser.

function ko(event, element) {
  if ('preventDefault' in event) event.preventDefault();
  event.returnValue = false; // for IE

  // here "element" will refer to the clicked-on element ...
}
like image 35
Pointy Avatar answered Oct 06 '22 00:10

Pointy