0

i am trying to use some javascript-code within an HTML-Page, but in doesn't work (Everything inside of a Ruby on Rails project). So i have the following HTML-Code

   <a href="#" compilation_id = 51 onclick="start_render(this)">Render</a>

What I need is to get the parameter "compilation_id" inside the js-function

  <script type="text/javascript" language="javascript">

  function start_render(event){  
         var comp_id = $(event.target).attr('compilation_id');
         alert(comp_id);
  .....

I use alert(comp_id) just for debugging in order to see, if I get the data appropriately. But what I get is "undefined". When I set the value of the variable inside of the js-function, everything is Ok. So,

  var comp_id = 51;
  alert(comp_id); 

works well, I get "51".

What is my mistake?

Thanks in advance.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
jenia
  • 55
  • 6
  • function start_render(event){ var comp_id = $(event).attr('compilation_id'); alert(comp_id); – Debadatt Jul 04 '13 at 13:45
  • http://jsfiddle.net/cPwNP/ use jquery – softsdev Jul 04 '13 at 13:48
  • add `class to anchor` link `eg: render` then put `$('.render').click(function(){ alert($(this).attr('compilation_id')); })` – softsdev Jul 04 '13 at 13:50
  • Consider using [`console.log`](http://stackoverflow.com/questions/4743730/what-is-console-log-and-how-do-i-use-it) instead of `alert()` for debugging – jacoz Jul 04 '13 at 13:59

2 Answers2

0

You are passing this object, which doesn't have target property.

If you want to get event target, change your code as

 function start_render(object){
     event = event || window.event 
     var comp_id = $(event.target).attr('compilation_id');
   ...
 }
Satpal
  • 132,252
  • 13
  • 159
  • 168
-2

try this:

onclick="start_render(event)"

JS:

function start_render(e){  
     var comp_id = $(e.target).attr('compilation_id');
     alert(comp_id); 

Or:

onclick="start_render(this)"

JS:

function start_render(element){  
     var comp_id = $(element).attr('compilation_id');
     alert(comp_id); 

Or:

onclick="start_render()"

JS:

function start_render(){  
     var comp_id = $(event.target).attr('compilation_id');
     alert(comp_id);

Or:

onclick="start_render.call(this)"

JS:

function start_render(){  
     var comp_id = $(this).attr('compilation_id');
     alert(comp_id);

Best way:

<a href="#" compilation_id="51" id="compilation51">Render</a>

JS:

$('#compilation51').bind('click', function(){
     var comp_id = $(this).attr('compilation_id');
     alert(comp_id);
});
karaxuna
  • 26,752
  • 13
  • 82
  • 117