Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call onclick attribute programmatically

I have a bunch of <a> tags on a page that look something like

 <a href="#" id="001" onclick="fnaaa();" >...</a>
  ...
 <a href="#" id="002" onclick="fnaba();" >...</a>
  ...
 <a href="#" id="003" onclick="fncda();" >...</a>


 //sometimes maybe like this
 <a href="#" id="004" onclick="fnagg(); return false;" >...</a>
  ...

Now I have the id passed to the page as a query string , so I originally wanted to do something like

$('a[id="' + id + '"]').click();
$('a[id="' + id + '"]').trigger("click");

it turns out both of those are not allowed , so if I have the id , how can I call the function that is written in the onclick attribute? I know I can probably get it like this

var funcToCall = $('a[id="' + id + '"]').attr('onclick');

but how do I call this funcToCall? remembering that funcToCall may be more then just a function name ex. "fnagg(); return false;"

like image 339
Scott Selby Avatar asked Mar 01 '13 20:03

Scott Selby


People also ask

How do you add onclick event dynamically?

Attaching the event dynamically className = 'dynamic-link'; // Class name li. innerHTML = dynamicValue; // Text inside $('#links'). appendChild(li); // Append it li. onclick = dynamicEvent; // Attach the event!

Is onclick attribute?

The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.


2 Answers

You are using onclick attribute to bind the handler. Try like below,

document.getElementById(id).click();

DEMO: http://jsfiddle.net/kpvKG/

like image 142
Selvakumar Arumugam Avatar answered Oct 15 '22 13:10

Selvakumar Arumugam


First of all, the ID attribute has some restrictions, one being that it must start with a letter. After you fix that, I would recommend not using an inline onclick handler.

$("#ID_HERE").click(function(e) {
  fnaaa();
  e.preventDefault();
});

Then you can trigger it easily:

$("#ID_HERE").triggerHandler("click");

However, if you absolutely must use the ugly onclick, you can invoke it like this:

<a id="foo" href="#" onclick="alert('test');">Test</a>
var el = document.getElementById('foo');
el.onclick();
like image 31
Josh Stodola Avatar answered Oct 15 '22 12:10

Josh Stodola