-1

When I create a new link dynamically, I can't catch the click event

$("#div").html("<a href="#" id="new">new link</a>);

$("#new").click(function(e) { //doesn't catch
   e.preventDefault();
   alert('click');
}

How can I bind handlers to dynamic elements?

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
Pipo
  • 5,170
  • 7
  • 33
  • 66

3 Answers3

3

Actually, this works fine for me: updated fiddle

You had a number of syntax errors in your original code.

$("#div").html("<a href='#' id='new'>new link</a>");
fixed quotes here ------^^^                      ^
fixed missing end quote here --------------------^

// works fine!
$("#new").click(function(e) {
    e.preventDefault();
    alert('click');
});
Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
  • no my example was written too quick without editor , it is a real question – Pipo Feb 10 '15 at 02:51
  • no, i made a mistake in my question but I am really trying to add item in DOM after loading – Pipo Feb 10 '15 at 03:05
  • I'm not sure why that fiddle isn't working for you; it works perfectly for me. What browser are you using? You have two options: use `setTimeout` to run the click binding code a few milliseconds delayed (not great), or try Sukima's suggestion of building the element with jQuery. – Nate Barbettini Feb 10 '15 at 03:08
1

You can't reference the created element by ID because it hasn't been added to the DOM yet and jQuery searches the DOM for ID's. Instead save a reference to the element and attach the click to that.

var div = $('<div>').attr('id', 'div');
var link = $('<a>')
  .attr('href', '#')
  .attr('id', 'new')
  .on('click', function(e) {
    e.preventDefault();
    alert('click');
  })
  .appendTo(div);
Sukima
  • 9,965
  • 3
  • 46
  • 60
  • attachTo doesn't seems exist – Pipo Feb 10 '15 at 03:01
  • That was supposed to say `appendTo`. fricken autocorrect. – Sukima Feb 10 '15 at 03:05
  • it is not really direct and not well written but it is a way! Thank you! – Pipo Feb 10 '15 at 03:56
  • Would you be interested to expand why you felt it wasn't well written? I'd be interested in learning a different perspective. As reference the above is a typical [fluent interface](http://en.wikipedia.org/wiki/Fluent_interface#JavaScript) ("There are many examples of JS libraries that use some variant of this: jQuery probably being the most well known.") Method chaining and the jQuery DSL is a well established and popular style to manage things like this. Composability offers a lot more flexibility and readability then sticking hacked up HTML strings in your code. – Sukima Feb 10 '15 at 14:59
-2

You should try this post out

It looks like it will answer your question.

To sum it up, try

$(".test").click(function () {
$.ajax({ url: 'http://.....your path...../accounts/index',
    data: {test:1},
    type: 'post',
    success: function(output) {
        //your code
             }
        }); 
});
Community
  • 1
  • 1
Brennan Macaig
  • 313
  • 1
  • 2
  • 9