9

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;"

Cœur
  • 32,421
  • 21
  • 173
  • 232
Scott Selby
  • 9,126
  • 12
  • 49
  • 91

5 Answers5

10

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();
Community
  • 1
  • 1
Josh Stodola
  • 77,975
  • 43
  • 178
  • 222
  • thanks , those are not my real id's , I just trying to simplify for an example . so people could see what I am trying to do - get the inline onclick attribute to be called dynamically while only knowing the id – Scott Selby Mar 01 '13 at 20:06
  • If you'd like to still use jQuery to select the element (for instance, if you want to select based off of something other than ids), you could trigger the onclick handler with `$(selector)[0].onclick();` – Jeremy T Mar 01 '13 at 20:14
  • Im getting Object [object Object] has no method 'onclick' with the jquery versioin $(selector)[0].onclick(); – Scott Selby Mar 01 '13 at 20:26
  • if you use addEventListener() you will not be getting any errors. onclick() is an attribute of the element so you can only assign one click action. Where addEventListener() you assign as many listeners to as many actions to any element you want. – Patrick W. McMahon Aug 29 '14 at 21:27
5

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

document.getElementById(id).click();

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

Selvakumar Arumugam
  • 76,636
  • 14
  • 118
  • 132
0

DEMO

function fnagg()
{
    alert('fired');
}
$(function(){
    eval("var funcToCall=function(){"+$('#004').attr("onclick")+"}");
funcToCall();
});
Kaizen Programmer
  • 3,748
  • 1
  • 12
  • 29
  • @Vega, You are correct, but it's the only way I know of to wrap a string in a function like the question is requesting. It's not really always evil...per the top voted answer here: http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – Kaizen Programmer Mar 01 '13 at 20:19
0

I would do something like this:

For the html

<a href="#" class="dynamicFuncs" id="my001" data-funcName="myFunc">test</a>

And for the javascript

$(document).ready(function(){
    $(".dynamicFuncs").on('click', function(){
        var theFunc = $(this).attr('data-funcName');
        window[theFunc]();
    })
});

var myFunc = function() {
    alert('me');
};
thitemple
  • 5,337
  • 3
  • 38
  • 62
-2

It's best to use addEventListener(). You can add all types of events. example: "click","mousemove" and many more. the false at the end is to stop the event from traversing up the DOM tree. By setting the 3rd property to true the event will continue to traverse the DOM tree so that parent elements will also receive the event. This also makes removing events just as simple as adding events using removeEventListener().

adding event

element.addEventListener(event, function, useCapture)

removing event

element.removeEventListener(event, function, useCapture)

event: Required. A String that specifies the name of the event.

function: Required. Specifies the function to run when the event occurs.

useCapture Optional. A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.

Possible values:

true - The event handler is executed in the capturing phase

false- Default. The event handler is executed in the bubbling phase

This example requires no JavaScript libraries. This is just plain old JavaScript and will work in every browser with nothing extra needed.

   <!DOCTYPE html>
    <html>
    <head>
    <title>exampe</title>
    </head>
    <body>
        <a id="test" href="">test</a>
    <script>
        document.getElementById("test").addEventListener("click", function(){
            alert('hello world');
        }, false);
    </script>
    </body>
    </html>

You can read more about this with the following links:


If you would like to use JQuery methods to handle a click event you can do the following.

Using .click()

$("#target").click(function() {
  alert("Handler for .click() called.");
});

More info here: https://api.jquery.com/click/

Using .on()

$("#target").on("click", function() {
  console.log($(this).text());
});

More info here: http://api.jquery.com/on/

Patrick W. McMahon
  • 3,059
  • 1
  • 15
  • 28