Maximus Decimus Maximus Decimus - 2 years ago 88
Javascript Question

Add onclick event to a dynamic-created anchor with JQuery

I found this question Use JQuery to build an anchor here to build an anchor dynamically with JQuery.

I want to know how can I add the onclick event to my hyperlink?

I've been trying to do this, but nothing happens. The onclick event is never added.

function init(){
var btnSave = "<a id=\"btnSave\">Save</a> "
$(btnSave).on("click", {Arg1 : "1", Arg2: "2"}, save)
var div = $("#myDiv");

function save(e){
var data =;
var arg1 = data.Arg1;
var arg2 = data.Arg2;

I know that I can "embeed" the onclick like this:

var btnSave = "<a id=\"btnSave\" onclick=\"" + ... + "\">Save</a> "

But the way I'm trying to do, it looks like cleaner in my opinion. I accept another cleaner option. Thanks.

My function save is planned to be reused many times with other hyperlinks the arguments are differents.


According to suggestions I changed it to this, but still cannot see the onclick added to my HTML element.

function init(){
var btnSave = $("<a id='btnSave'></a>").html("Save").on("click", {Arg1 : "1", Arg2: "2"}, save);

In the console of Google chrome I test the value of the btnSave and the console logs this

"<a id="btnSave">Save</a>"

Answer Source

This line of code:


… is equivalent to this:

div.html("<a id=\"btnSave\">Save</a> ");

The anchor created with the following code is essentially being lost, because it isn't ever attached to the DOM:

$(btnSave).on("click", {Arg1 : "1", Arg2: "2"}, save);

Instead, you could store that anchor in a new variable, which you can put in the DIV:

function init(){
  var btnSave = "<a id=\"btnSave\">Save</a> ",
      anchor = $(btnSave).on("click", {Arg1 : "1", Arg2: "2"}, save);

  var div = $("#myDiv");

Or more simply:

function init(){
  var anchor= $('<a id="btnSave">Save</a> ')
                .on('click', {Arg1 : '1', Arg2: '2'}, save)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download